<?php
// ============================================================
// Elegant Work — Meetings API
// POST /api/meetings/index.php  action=list|get|save|delete
// ============================================================
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user   = requireAuth();
$db     = getDB();
$uid    = (int)$user['id'];
$action = post('action', 'list');

switch ($action) {

// ── LIST ─────────────────────────────────────────────────────
case 'list': {
    $p       = getPagination();
    $search  = post('search', '');
    $type    = post('type', '');
    $status  = post('status', '');
    $from    = post('date_from', '');
    $to      = post('date_to', '');
    $myOnly  = (int)post('my_only', 0);

    $where  = ['1=1'];
    $params = [];

    if ($search) {
        $where[]  = '(m.title LIKE ? OR m.description LIKE ? OR m.location LIKE ?)';
        $params   = array_merge($params, ["%$search%", "%$search%", "%$search%"]);
    }
    if ($type)   { $where[] = 'm.type = ?';   $params[] = $type; }
    if ($status) { $where[] = 'm.status = ?'; $params[] = $status; }
    if ($from)   { $where[] = 'm.meeting_date >= ?'; $params[] = $from; }
    if ($to)     { $where[] = 'm.meeting_date <= ?'; $params[] = $to; }

    // "My meetings" = created by me OR I'm an attendee
    if ($myOnly || !(in_array((int)$user['role_id'], [1, 2]))) {
        $where[]  = '(m.created_by = ? OR EXISTS (SELECT 1 FROM meeting_attendees ma WHERE ma.meeting_id = m.id AND ma.user_id = ?))';
        $params[] = $uid;
        $params[] = $uid;
    }

    $ws = implode(' AND ', $where);

    $countStmt = $db->prepare("SELECT COUNT(*) FROM meetings m WHERE $ws");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    $stmt = $db->prepare("
        SELECT m.*,
               u.full_name  AS created_by_name,
               c.company_name AS client_name,
               (SELECT COUNT(*) FROM meeting_attendees ma WHERE ma.meeting_id = m.id) AS attendee_count,
               (SELECT COUNT(*) FROM meeting_attendees ma WHERE ma.meeting_id = m.id AND ma.rsvp_status = 'accepted') AS accepted_count,
               (SELECT COUNT(*) FROM meeting_attendees ma WHERE ma.meeting_id = m.id AND ma.rsvp_status = 'declined') AS declined_count
        FROM meetings m
        LEFT JOIN users u   ON u.id = m.created_by
        LEFT JOIN clients c ON c.id = m.client_id
        WHERE $ws
        ORDER BY m.meeting_date DESC, m.start_time DESC
        LIMIT {$p['limit']} OFFSET {$p['offset']}
    ");
    $stmt->execute($params);
    $meetings = $stmt->fetchAll();

    apiSuccess([
        'meetings'   => $meetings,
        'pagination' => ['total' => $total, 'page' => $p['page'], 'limit' => $p['limit'], 'pages' => ceil($total / $p['limit'])],
    ]);
}

// ── GET single ───────────────────────────────────────────────
case 'get': {
    $id = (int)post('id', 0);
    if (!$id) apiError('ID required.', 422);

    $stmt = $db->prepare("
        SELECT m.*,
               u.full_name AS created_by_name,
               c.company_name AS client_name
        FROM meetings m
        LEFT JOIN users u   ON u.id = m.created_by
        LEFT JOIN clients c ON c.id = m.client_id
        WHERE m.id = ?
    ");
    $stmt->execute([$id]);
    $meeting = $stmt->fetch();
    if (!$meeting) apiError('Meeting not found.', 404);

    // Attendees
    $aStmt = $db->prepare("
        SELECT ma.*,
               u.full_name AS user_name, u.email AS user_email,
               cc.full_name AS contact_name, cc.email AS contact_email
        FROM meeting_attendees ma
        LEFT JOIN users u ON u.id = ma.user_id
        LEFT JOIN client_contacts cc ON cc.id = ma.contact_id
        WHERE ma.meeting_id = ?
        ORDER BY ma.type, ma.id
    ");
    $aStmt->execute([$id]);
    $meeting['attendees'] = $aStmt->fetchAll();

    // Notes
    $nStmt = $db->prepare("
        SELECT mn.*, u.full_name AS user_name
        FROM meeting_notes mn
        JOIN users u ON u.id = mn.user_id
        WHERE mn.meeting_id = ?
        ORDER BY mn.created_at ASC
    ");
    $nStmt->execute([$id]);
    $meeting['notes'] = $nStmt->fetchAll();

    // Files
    $fStmt = $db->prepare("
        SELECT mf.*, u.full_name AS uploaded_by_name
        FROM meeting_files mf
        JOIN users u ON u.id = mf.user_id
        WHERE mf.meeting_id = ?
        ORDER BY mf.created_at ASC
    ");
    $fStmt->execute([$id]);
    $meeting['files'] = $fStmt->fetchAll();

    // For tasks — fetch sub-checklist items
    if ($meeting['type'] === 'task') {
        $tiStmt = $db->prepare("SELECT * FROM meeting_task_items WHERE meeting_id=? ORDER BY sort_order,id");
        $tiStmt->execute([$id]);
        $meeting['task_items'] = $tiStmt->fetchAll();
    }

    apiSuccess(['meeting' => $meeting]);
}

// ── SAVE (create / update) ────────────────────────────────────
case 'save': {
    require_once __DIR__ . '/../config/mailer.php';
    require_once __DIR__ . '/../emails/templates.php';

    $id = (int)post('id', 0);
    $title = trim(post('title', ''));
    $meetingDate = post('meeting_date', '');

    if (!$title)       apiError('Title is required.', 422);
    if (!$meetingDate) apiError('Date is required.', 422);

    $fields = [
        'type'         => post('type', 'internal'),
        'title'        => $title,
        'description'  => post('description', ''),
        'location'     => post('location', ''),
        'meeting_date' => $meetingDate,
        'start_time'   => post('start_time') ?: null,
        'end_time'     => post('end_time') ?: null,
        'all_day'      => post('all_day') ? 1 : 0,
        'priority'     => post('priority', 'normal'),
        'color'        => post('color', 'blue'),
        'client_id'    => post('client_id') ?: null,
        'project_id'   => post('project_id') ?: null,
        'notes'        => post('notes', ''),
    ];

    $db->beginTransaction();

    if ($id) {
        $sets = implode(',', array_map(fn($k) => "$k=?", array_keys($fields)));
        $db->prepare("UPDATE meetings SET $sets WHERE id=?")->execute([...array_values($fields), $id]);
    } else {
        $cols   = implode(',', array_keys($fields));
        $places = implode(',', array_fill(0, count($fields), '?'));
        $db->prepare("INSERT INTO meetings ($cols, created_by) VALUES ($places, ?)")->execute([...array_values($fields), $uid]);
        $id = (int)$db->lastInsertId();
    }

    // ── Sync attendees ────────────────────────────────────────
    $attendeesRaw = post('attendees', []);
    if (!is_array($attendeesRaw)) $attendeesRaw = [];

    // Get existing attendees (for invite tracking)
    $existingStmt = $db->prepare("SELECT id, user_id, contact_id, email, rsvp_token, invite_sent FROM meeting_attendees WHERE meeting_id = ?");
    $existingStmt->execute([$id]);
    $existing = $existingStmt->fetchAll();
    $existingByKey = [];
    foreach ($existing as $ea) {
        $key = $ea['user_id'] ? "u:{$ea['user_id']}" : ($ea['contact_id'] ? "c:{$ea['contact_id']}" : "e:{$ea['email']}");
        $existingByKey[$key] = $ea;
    }

    // Delete all and reinsert (simpler than diff)
    $db->prepare("DELETE FROM meeting_attendees WHERE meeting_id = ?")->execute([$id]);

    $newAttendees = [];
    $sendInvites  = post('send_invites') ? true : false;

    foreach ($attendeesRaw as $att) {
        $type      = $att['type'] ?? 'user';
        $userId    = !empty($att['user_id'])   ? (int)$att['user_id']   : null;
        $contactId = !empty($att['contact_id'])? (int)$att['contact_id']: null;
        $name      = trim($att['name']  ?? '');
        $email     = trim($att['email'] ?? '');

        // Resolve email/name from user or contact if not provided
        if ($userId && !$email) {
            $uRow = $db->prepare("SELECT full_name, email FROM users WHERE id=? LIMIT 1");
            $uRow->execute([$userId]);
            $uData = $uRow->fetch();
            $email = $uData['email'] ?? '';
            $name  = $name ?: ($uData['full_name'] ?? '');
        }
        if ($contactId && !$email) {
            $ccRow = $db->prepare("SELECT full_name, email FROM client_contacts WHERE id=? LIMIT 1");
            $ccRow->execute([$contactId]);
            $ccData = $ccRow->fetch();
            $email  = $ccData['email'] ?? '';
            $name   = $name ?: ($ccData['full_name'] ?? '');
        }

        if (!$email) continue;

        // Keep existing RSVP token if re-saving
        $key     = $userId ? "u:{$userId}" : ($contactId ? "c:{$contactId}" : "e:{$email}");
        $token   = $existingByKey[$key]['rsvp_token'] ?? bin2hex(random_bytes(24));
        $invited = $existingByKey[$key]['invite_sent'] ?? 0;

        $db->prepare("
            INSERT INTO meeting_attendees (meeting_id, type, user_id, contact_id, name, email, rsvp_token, invite_sent)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([$id, $type, $userId, $contactId, $name, $email, $token, $invited]);

        $newAttendees[] = [
            'db_id'    => (int)$db->lastInsertId(),
            'name'     => $name,
            'email'    => $email,
            'token'    => $token,
            'invited'  => $invited,
            'is_new'   => !isset($existingByKey[$key]),
        ];
    }

    $db->commit();

    // ── Send invites ─────────────────────────────────────────
    if ($sendInvites) {
        try {
            $cfg     = getMailerConfig($db);
            $appUrl  = $cfg['email_app_url'] ?? '';
            $compStmt = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_name' LIMIT 1");
            $companyName = $compStmt ? ($compStmt->fetchColumn() ?: 'Elegant Work') : 'Elegant Work';

            $meetingData = [
                'id'           => $id,
                'title'        => $fields['title'],
                'type'         => $fields['type'],
                'meeting_date' => $fields['meeting_date'],
                'start_time'   => $fields['start_time'],
                'end_time'     => $fields['end_time'],
                'location'     => $fields['location'],
                'description'  => $fields['description'],
                'priority'     => $fields['priority'],
            ];

            foreach ($newAttendees as $att) {
                if (!$att['email'] || (!$att['is_new'] && $att['invited'])) continue;
                $rsvpBase = $appUrl . 'api/meetings/rsvp.php?token=' . $att['token'];
                $html = tplMeetingInvite($meetingData, $att['name'] ?: 'Guest', $companyName, $rsvpBase);
                queueEmail($db, 'meeting_invite', $att['email'], $att['name'],
                    "📅 Meeting Invitation: {$fields['title']}", $html, 'meeting', $id);
                $db->prepare("UPDATE meeting_attendees SET invite_sent=1, invite_sent_at=NOW() WHERE meeting_id=? AND email=?")
                   ->execute([$id, $att['email']]);
            }
        } catch (Exception $e) {
            error_log('[EWG Meetings] invite send failed: ' . $e->getMessage());
        }
    }

    apiSuccess(['id' => $id], $id ? 'Meeting saved.' : 'Meeting created.', 201);
}

// ── START meeting (set status = in_progress) ─────────────────
case 'start': {
    $id = (int)post('id', 0);
    if (!$id) apiError('ID required.', 422);
    $db->prepare("UPDATE meetings SET status='in_progress' WHERE id=?")->execute([$id]);
    apiSuccess(['id' => $id], 'Meeting started.');
}

// ── COMPLETE meeting ──────────────────────────────────────────
case 'complete': {
    $id = (int)post('id', 0);
    if (!$id) apiError('ID required.', 422);
    $notes = post('notes', '');
    $db->prepare("UPDATE meetings SET status='completed', notes=? WHERE id=?")->execute([$notes, $id]);
    apiSuccess(['id' => $id], 'Meeting completed.');
}

// ── DELETE ────────────────────────────────────────────────────
case 'delete': {
    $id = (int)post('id', 0);
    if (!$id) apiError('ID required.', 422);
    // Only creator or admin can delete
    $row = $db->prepare("SELECT created_by FROM meetings WHERE id=? LIMIT 1");
    $row->execute([$id]);
    $m = $row->fetch();
    if (!$m) apiError('Not found.', 404);
    if ((int)$m['created_by'] !== $uid && (int)$user['role_id'] !== 1) apiError('Permission denied.', 403);
    $db->prepare("DELETE FROM meetings WHERE id=?")->execute([$id]);
    apiSuccess([], 'Meeting deleted.');
}

// ── SAVE NOTE ─────────────────────────────────────────────────
case 'save_note': {
    $meetingId = (int)post('meeting_id', 0);
    $content   = trim(post('content', ''));
    $noteId    = (int)post('note_id', 0);
    if (!$meetingId || !$content) apiError('Meeting ID and content required.', 422);
    if ($noteId) {
        $db->prepare("UPDATE meeting_notes SET content=?, updated_at=NOW() WHERE id=? AND user_id=?")
           ->execute([$content, $noteId, $uid]);
    } else {
        $db->prepare("INSERT INTO meeting_notes (meeting_id, user_id, content) VALUES (?,?,?)")
           ->execute([$meetingId, $uid, $content]);
        $noteId = (int)$db->lastInsertId();
    }
    apiSuccess(['note_id' => $noteId, 'user_name' => $user['full_name'], 'content' => $content, 'created_at' => date('Y-m-d H:i:s')], 'Note saved.');
}

// ── RESEND INVITE ─────────────────────────────────────────────
case 'resend_invite': {
    require_once __DIR__ . '/../config/mailer.php';
    require_once __DIR__ . '/../emails/templates.php';
    $meetingId   = (int)post('meeting_id', 0);
    $attendeeId  = (int)post('attendee_id', 0);
    if (!$meetingId || !$attendeeId) apiError('IDs required.', 422);

    $mStmt = $db->prepare("SELECT * FROM meetings WHERE id=? LIMIT 1");
    $mStmt->execute([$meetingId]);
    $m = $mStmt->fetch();
    if (!$m) apiError('Meeting not found.', 404);

    $aStmt = $db->prepare("SELECT * FROM meeting_attendees WHERE id=? AND meeting_id=? LIMIT 1");
    $aStmt->execute([$attendeeId, $meetingId]);
    $att = $aStmt->fetch();
    if (!$att || !$att['email']) apiError('Attendee not found.', 404);

    $cfg     = getMailerConfig($db);
    $appUrl  = $cfg['email_app_url'] ?? '';
    $compStmt = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_name' LIMIT 1");
    $companyName = $compStmt ? ($compStmt->fetchColumn() ?: 'Elegant Work') : 'Elegant Work';
    $rsvpBase = $appUrl . 'api/meetings/rsvp.php?token=' . $att['rsvp_token'];
    $html = tplMeetingInvite($m, $att['name'] ?: 'Guest', $companyName, $rsvpBase);
    queueEmail($db, 'meeting_invite', $att['email'], $att['name'],
        "📅 Meeting Invitation: {$m['title']}", $html, 'meeting', $meetingId);
    $db->prepare("UPDATE meeting_attendees SET invite_sent=1, invite_sent_at=NOW() WHERE id=?")->execute([$attendeeId]);
    apiSuccess([], 'Invite queued.');
}


// ── TASK ITEMS (sub-checklist) ────────────────────────────────
case 'task_items': {
    $sub    = post('sub', 'list'); // list|add|toggle|delete|reorder
    $taskId = (int)post('task_id', 0);
    if (!$taskId) apiError('task_id required.', 422);

    if ($sub === 'list') {
        $rows = $db->prepare("SELECT * FROM meeting_task_items WHERE meeting_id=? ORDER BY sort_order,id");
        $rows->execute([$taskId]);
        apiSuccess(['items' => $rows->fetchAll()]);
    }
    if ($sub === 'add') {
        $text = trim(post('text',''));
        if (!$text) apiError('Text required.', 422);
        $db->prepare("INSERT INTO meeting_task_items (meeting_id,text,sort_order) VALUES (?,?,(SELECT COALESCE(MAX(sort_order),0)+1 FROM meeting_task_items t2 WHERE t2.meeting_id=?))")
           ->execute([$taskId, $text, $taskId]);
        $newId = (int)$db->lastInsertId();
        apiSuccess(['id'=>$newId,'text'=>$text,'is_done'=>0], 'Item added.');
    }
    if ($sub === 'toggle') {
        $itemId = (int)post('item_id',0);
        $done   = post('done') ? 1 : 0;
        $db->prepare("UPDATE meeting_task_items SET is_done=? WHERE id=? AND meeting_id=?")->execute([$done,$itemId,$taskId]);
        apiSuccess(['id'=>$itemId,'is_done'=>$done]);
    }
    if ($sub === 'delete') {
        $itemId = (int)post('item_id',0);
        $db->prepare("DELETE FROM meeting_task_items WHERE id=? AND meeting_id=?")->execute([$itemId,$taskId]);
        apiSuccess([], 'Deleted.');
    }
    if ($sub === 'rename') {
        $itemId = (int)post('item_id',0);
        $text   = trim(post('text',''));
        if (!$text) apiError('Text required.',422);
        $db->prepare("UPDATE meeting_task_items SET text=? WHERE id=? AND meeting_id=?")->execute([$text,$itemId,$taskId]);
        apiSuccess([], 'Updated.');
    }
    apiError('Unknown sub-action.',400);
}


case 'toggle_complete': {
    $id     = (int)post('id', 0);
    $done   = post('done') ? 1 : 0;
    if (!$id) apiError('ID required.', 422);
    $status = $done ? 'completed' : 'scheduled';
    $db->prepare("UPDATE meetings SET status=? WHERE id=? AND (created_by=? OR 1=1)")->execute([$status, $id, $uid]);
    apiSuccess(['id' => $id, 'status' => $status], $done ? 'Marked complete.' : 'Marked incomplete.');
}

// ── DISMISS / SNOOZE reminder ─────────────────────────────────
case 'dismiss_reminder': {
    $id = (int)post('id', 0);
    if (!$id) apiError('ID required.', 422);
    $db->prepare("UPDATE meetings SET status='completed' WHERE id=?")->execute([$id]);
    apiSuccess([], 'Reminder dismissed.');
}

case 'snooze_reminder': {
    $id      = (int)post('id', 0);
    $newDate = post('new_date', '');
    $newTime = post('new_time', '') ?: null;
    if (!$id || !$newDate) apiError('ID and new_date required.', 422);
    $db->prepare("UPDATE meetings SET meeting_date=?, start_time=?, status='scheduled' WHERE id=?")->execute([$newDate, $newTime, $id]);
    apiSuccess([], 'Reminder snoozed.');
}

default:
    apiError('Unknown action.', 400);
}