<?php
require_once 'config/db.php';

$meeting_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$m = [
    'lead_id' => '', 'title' => '', 'meeting_date' => date('Y-m-d'), 'start_time' => '10:00', 'end_time' => '11:00',
    'location' => '', 'status' => 'scheduled', 'notes' => '',
    'meeting_type' => 'live_meeting', 'meeting_link' => ''
];
$is_edit = false;

// If editing, load existing data
if ($meeting_id) {
    $stmt = $pdo->prepare("SELECT * FROM meetings WHERE id = ?");
    $stmt->execute([$meeting_id]);
    $existing = $stmt->fetch();
    if ($existing) {
        $m = $existing;
        $m['start_time'] = substr($m['start_time'], 0, 5); // Format HH:MM
        $m['end_time'] = substr($m['end_time'], 0, 5);
        $is_edit = true;
    } else {
        header("Location: meetings.php");
        exit;
    }
}

// Optionally pre-select Lead if passed via GET
if (isset($_GET['lead_id']) && !$is_edit) {
    $m['lead_id'] = (int)$_GET['lead_id'];
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title        = trim($_POST['title']);
    $lead_id      = !empty($_POST['lead_id']) ? (int)$_POST['lead_id'] : null;
    $date         = trim($_POST['meeting_date']);
    $start_time   = trim($_POST['start_time']);
    $end_time     = trim($_POST['end_time']);
    $location     = trim($_POST['location']);
    $status       = trim($_POST['status']);
    $notes        = trim($_POST['notes']);
    $meeting_type = trim($_POST['meeting_type'] ?? 'live_meeting');
    $meeting_link = trim($_POST['meeting_link'] ?? '');

    // Only store link for online meeting
    if ($meeting_type !== 'online_meeting') $meeting_link = '';

    if (empty($title) || empty($date) || empty($start_time) || empty($end_time)) {
        $error = "Title, Date, Start Time, and End Time are required.";
    } else {
        try {
            if ($is_edit) {
                $stmt = $pdo->prepare("UPDATE meetings SET lead_id=?, title=?, meeting_date=?, start_time=?, end_time=?, location=?, status=?, notes=?, meeting_type=?, meeting_link=? WHERE id=?");
                $stmt->execute([$lead_id, $title, $date, $start_time, $end_time, $location, $status, $notes, $meeting_type, $meeting_link, $meeting_id]);
                $success = "Meeting updated successfully!";
            } else {
                $stmt = $pdo->prepare("INSERT INTO meetings (lead_id, title, meeting_date, start_time, end_time, location, status, notes, meeting_type, meeting_link) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$lead_id, $title, $date, $start_time, $end_time, $location, $status, $notes, $meeting_type, $meeting_link]);
                $success = "Meeting scheduled successfully!";
                $is_edit = true;
                $meeting_id = $pdo->lastInsertId();
            }
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
    
    $m['title'] = $title; $m['lead_id'] = $lead_id; $m['meeting_date'] = $date;
    $m['start_time'] = $start_time; $m['end_time'] = $end_time;
    $m['location'] = $location; $m['status'] = $status; $m['notes'] = $notes;
    $m['meeting_type'] = $meeting_type; $m['meeting_link'] = $meeting_link;
}

$leads = $pdo->query("SELECT id, name, phone FROM leads WHERE is_junk = 0 ORDER BY name ASC")->fetchAll();

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
        <h2><?= $is_edit ? '<i class="fa-solid fa-pen-to-square"></i> Edit Meeting' : '<i class="fa-solid fa-calendar-plus"></i> Schedule New Meeting' ?></h2>
        <a href="meetings.php" style="color:var(--text-main); text-decoration: none; font-weight: 500;"><i class="fa-solid fa-arrow-left"></i> Back to Meetings</a>
    </div>

    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="data-card" style="background:#fff; padding:30px; border-radius:12px; box-shadow:0 4px 15px rgba(0,0,0,0.03);">
        <form action="meeting_add_edit.php<?= $is_edit ? '?edit='.$meeting_id : '' ?>" method="POST">
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Meeting Title*</label>
                    <input type="text" name="title" required value="<?= htmlspecialchars($m['title']) ?>" placeholder="e.g. Site Visit with John" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Related Lead (Optional)</label>
                    <select name="lead_id" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; background:#f8fafc; font-family:inherit;">
                        <option value="">-- General / No Specific Lead --</option>
                        <?php foreach($leads as $lead): ?>
                            <option value="<?= $lead['id'] ?>" <?= $m['lead_id'] == $lead['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($lead['name']) ?> (<?= htmlspecialchars($lead['phone']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Date*</label>
                    <input type="date" name="meeting_date" required value="<?= htmlspecialchars($m['meeting_date']) ?>" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Start Time*</label>
                    <input type="time" name="start_time" required value="<?= htmlspecialchars($m['start_time']) ?>" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">End Time*</label>
                    <input type="time" name="end_time" required value="<?= htmlspecialchars($m['end_time']) ?>" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
            </div>

            <!-- Meeting Type selector -->
            <div style="margin-bottom:22px;">
                <label style="display:block; margin-bottom:12px; font-weight:600; font-size:0.9rem;">Meeting Type*</label>
                <div style="display:flex; gap:12px; flex-wrap:wrap;">
                    <?php
                    $types = [
                        'live_meeting'   => ['fa-people-group',  'Live Meeting',   '#3b82f6', 'In-person at office or venue'],
                        'site_visit'     => ['fa-hard-hat',      'Site Visit',     '#f59e0b', 'Visit the construction site'],
                        'online_meeting' => ['fa-video',         'Online Meeting', '#8b5cf6', 'Zoom / Teams / Google Meet'],
                    ];
                    foreach ($types as $val => [$icon, $label, $color, $desc]): $checked = ($m['meeting_type'] === $val); ?>
                    <label for="mt_<?= $val ?>" style="flex:1; min-width:140px; cursor:pointer;">
                        <input type="radio" name="meeting_type" id="mt_<?= $val ?>" value="<?= $val ?>" <?= $checked ? 'checked' : '' ?> style="display:none;" onchange="handleMeetingType()">
                        <div class="mtype-card <?= $checked ? 'mtype-active' : '' ?>" id="mcard_<?= $val ?>" style="border:2px solid <?= $checked ? $color : '#e2e8f0' ?>; border-radius:10px; padding:14px 16px; background:<?= $checked ? $color.'12' : '#fff' ?>; transition:all 0.2s;">
                            <div style="display:flex; align-items:center; gap:10px; margin-bottom:4px;">
                                <i class="fa-solid <?= $icon ?>" style="color:<?= $color ?>; font-size:1.1rem;"></i>
                                <span style="font-weight:700; color:var(--dark);"><?= $label ?></span>
                            </div>
                            <div style="font-size:0.78rem; color:#64748b;"><?= $desc ?></div>
                        </div>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Online Meeting Link (shown only for online_meeting) -->
            <div id="meeting_link_row" style="margin-bottom:22px; <?= $m['meeting_type'] !== 'online_meeting' ? 'display:none;' : '' ?>">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;"><i class="fa-solid fa-link" style="color:#8b5cf6; margin-right:6px;"></i>Online Meeting Link</label>
                <input type="url" name="meeting_link" id="meeting_link" value="<?= htmlspecialchars($m['meeting_link'] ?? '') ?>" 
                    placeholder="https://zoom.us/j/... or Google Meet / Teams link"
                    style="width:100%; padding:12px 15px; border:2px solid #8b5cf6; border-radius:8px; font-family:inherit; background:#faf7ff;">
                <div style="font-size:0.78rem; color:#8b5cf6; margin-top:5px;"><i class="fa-solid fa-circle-info"></i> Paste your full Zoom, Google Meet, or Teams URL here.</div>
            </div>

            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 25px;">
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Location / Address</label>
                    <input type="text" name="location" value="<?= htmlspecialchars($m['location']) ?>" placeholder="Office address, site address, or venue" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Status</label>
                    <select name="status" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; background:#f8fafc; font-family:inherit;">
                        <option value="scheduled"   <?= $m['status'] == 'scheduled'   ? 'selected' : '' ?>>Scheduled</option>
                        <option value="completed"   <?= $m['status'] == 'completed'   ? 'selected' : '' ?>>Completed</option>
                        <option value="rescheduled" <?= $m['status'] == 'rescheduled' ? 'selected' : '' ?>>Rescheduled</option>
                        <option value="cancelled"   <?= $m['status'] == 'cancelled'   ? 'selected' : '' ?>>Cancelled</option>
                    </select>
                </div>
            </div>

            <div style="margin-bottom: 25px;">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Meeting Agenda / Notes</label>
                <textarea name="notes" rows="4" placeholder="What will be discussed?" style="width:100%; padding:12px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"><?= htmlspecialchars($m['notes']) ?></textarea>
            </div>

            <div style="border-top: 1px solid var(--border); padding-top: 20px; text-align: right;">
                <button type="submit" style="padding: 12px 30px; background: var(--primary); color: #fff; border: none; border-radius: 6px; font-weight: 600; font-size: 1rem; cursor: pointer; display: inline-flex; align-items: center;"><i class="fa-solid fa-save" style="margin-right: 8px;"></i> <?= $is_edit ? 'Update Meeting' : 'Save Meeting' ?></button>
            </div>
        </form>
    </div>
</div>

<script>
const typeColors = {
    'live_meeting':   '#3b82f6',
    'site_visit':     '#f59e0b',
    'online_meeting': '#8b5cf6'
};

function handleMeetingType() {
    const selected = document.querySelector('input[name="meeting_type"]:checked')?.value;
    
    // Update card visuals
    Object.keys(typeColors).forEach(val => {
        const card = document.getElementById('mcard_' + val);
        const color = typeColors[val];
        if (val === selected) {
            card.style.border = '2px solid ' + color;
            card.style.background = color + '12';
        } else {
            card.style.border = '2px solid #e2e8f0';
            card.style.background = '#fff';
        }
    });

    // Show/hide online link
    const linkRow = document.getElementById('meeting_link_row');
    linkRow.style.display = (selected === 'online_meeting') ? 'block' : 'none';
    
    if (selected !== 'online_meeting') {
        document.getElementById('meeting_link').value = '';
    }
}

// Init on load
document.addEventListener('DOMContentLoaded', handleMeetingType);
</script>

<style>
@media (max-width: 768px) {
    .data-card form > div[style*="grid-template-columns"] {
        grid-template-columns: 1fr !important;
        gap: 15px !important;
    }
    .mtype-card { padding: 11px 12px !important; }
}
</style>

<?php require_once 'includes/footer.php'; ?>
