<?php
/**
 * Chat API Endpoint
 * Handles fetching participant details for the Firebase chat.
 */



header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'bootstrap.php';
require_once '../admin/includes/notification_helper.php';

// Check authentication - relaxed for API support
$user_id = $_GET['user_id'] ?? $_POST['user_id'] ?? $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? null;

if (!$user_id && $_SERVER['REQUEST_METHOD'] !== 'OPTIONS') {
    // If no user_id in params/session, still allow if it's a POST with json body
    $input = json_decode(file_get_contents('php://input'), true);
    if (!isset($input['user_id'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }
}

$pdo = getDBConnection();
if (!$pdo) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database connection failed']);
    exit;
}

// Ensure is_read column exists
try {
    $pdo->query("SELECT is_read FROM chats LIMIT 1");
} catch (Exception $e) {
    $pdo->query("ALTER TABLE chats ADD COLUMN is_read TINYINT(1) DEFAULT 0");
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? 'get_messages';
    $booking_id = $_GET['booking_id'] ?? null;

    if (!$booking_id) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Booking ID required']);
        exit;
    }

    if ($action === 'get_participants') {
        // Fetch participant details for the chat UI
        $stmt = $pdo->prepare("
            SELECT b.reference_number, 
                   u.first_name as client_name, u.last_name as client_last_name,
                   d.first_name as driver_name, d.last_name as driver_last_name
            FROM bookings b
            LEFT JOIN users u ON b.user_id = u.id
            LEFT JOIN drivers d ON b.driver_id = d.id
            WHERE b.id = ?
        ");
        $stmt->execute([$booking_id]);
        $data = $stmt->fetch();

        if ($data) {
            echo json_encode(['success' => true, 'data' => $data]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Booking not found']);
        }
        exit;
    }

    if ($action === 'get_unread_count') {
        $sender_type = $_GET['sender_type'] ?? 'customer';
        $user_id = $_GET['user_id'] ?? $_POST['user_id'] ?? $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? null;

        if (!$user_id) {
            echo json_encode(['success' => true, 'unread_count' => 0]);
            exit;
        }

        if ($sender_type === 'admin') {
            // Count all messages sent by customers/drivers that are unread
            $stmt = $pdo->prepare("SELECT COUNT(*) as unread FROM chats WHERE sender_type != 'admin' AND is_read = 0");
            $stmt->execute();
        } else {
            // Count all messages sent by admin for this user's bookings that are unread
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as unread
                FROM chats c
                JOIN bookings b ON c.booking_id = b.id
                WHERE b.user_id = ? AND c.sender_type = 'admin' AND c.is_read = 0
            ");
            $stmt->execute([$user_id]);
        }
        $row = $stmt->fetch();
        echo json_encode(['success' => true, 'unread_count' => (int)$row['unread']]);
        exit;
    }

    // Fallback mode: fetch messages from local database
    $last_id = intval($_GET['last_id'] ?? 0);

    // Mark as read when fetching
    $sender_type = $_GET['sender_type'] ?? 'customer';
    if ($sender_type === 'admin') {
        $updateStmt = $pdo->prepare("UPDATE chats SET is_read = 1 WHERE booking_id = ? AND sender_type != 'admin'");
        $updateStmt->execute([$booking_id]);
    } else {
        $updateStmt = $pdo->prepare("UPDATE chats SET is_read = 1 WHERE booking_id = ? AND sender_type = 'admin'");
        $updateStmt->execute([$booking_id]);
    }

    $stmt = $pdo->prepare("
        SELECT c.*,
               COALESCE(u.first_name, a.first_name) as first_name,
               COALESCE(u.last_name, a.last_name) as last_name,
               c.sender_type
        FROM chats c
        LEFT JOIN users u ON c.sender_id = u.id AND c.sender_type != 'admin'
        LEFT JOIN admin_users a ON c.sender_id = a.id AND c.sender_type = 'admin'
        WHERE c.booking_id = ? AND c.id > ?
        ORDER BY c.created_at ASC
    ");
    $stmt->execute([$booking_id, $last_id]);
    $messages = $stmt->fetchAll();

    echo json_encode(['success' => true, 'messages' => $messages]);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Legacy support for sending messages to local DB
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? $_POST['action'] ?? 'send_message';
    $booking_id = $input['booking_id'] ?? $_POST['booking_id'] ?? null;
    $message = trim($input['message'] ?? $_POST['message'] ?? '');
    $user_id = $input['user_id'] ?? $_POST['user_id'] ?? $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? null;

    // Determine sender type
    $sender_type = $input['sender_type'] ?? $_POST['sender_type'] ?? null;
    if (!$sender_type) {
        if (isset($_SESSION['admin_logged_in'])) {
            $sender_type = 'admin';
        } else {
            $sender_type = 'customer';
        }
    }

    if ($action === 'edit_message') {
        $message_id = $input['message_id'] ?? $_POST['message_id'] ?? null;
        if ($message_id && !empty($message) && $user_id) {
            $stmt = $pdo->prepare("UPDATE chats SET message = ? WHERE id = ? AND sender_id = ? AND sender_type = ?");
            $stmt->execute([$message, $message_id, $user_id, $sender_type]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing data']);
        }
        exit;
    }

    if ($action === 'delete_message') {
        $message_id = $input['message_id'] ?? $_POST['message_id'] ?? null;
        if ($message_id && $user_id) {
            $stmt = $pdo->prepare("DELETE FROM chats WHERE id = ? AND sender_id = ? AND sender_type = ?");
            $stmt->execute([$message_id, $user_id, $sender_type]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing data']);
        }
        exit;
    }

    if (!$booking_id || empty($message) || !$user_id) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Booking ID, message, and User ID are required']);
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO chats (booking_id, sender_id, sender_type, message) VALUES (?, ?, ?, ?)");
    $stmt->execute([$booking_id, $user_id, $sender_type, $message]);
    $message_id = $pdo->lastInsertId();

    // Trigger notification
    try {
        $stmt = $pdo->prepare("SELECT user_id, reference_number FROM bookings WHERE id = ?");
        $stmt->execute([$booking_id]);
        $booking = $stmt->fetch();

        if ($booking) {
            $sender_name = 'Someone';
            if ($sender_type === 'admin') {
                $stmt = $pdo->prepare("SELECT first_name FROM admin_users WHERE id = ?");
                $stmt->execute([$user_id]);
                $sender_name = $stmt->fetchColumn() ?: 'Admin';

                addNotification(
                    $booking['user_id'],
                    "New message from Admin",
                    "Admin: " . (strlen($message) > 50 ? substr($message, 0, 47) . '...' : $message),
                    'info',
                    "chat_screen.dart?booking_id=" . $booking_id,
                    'customer'
                );
            } else {
                $stmt = $pdo->prepare("SELECT first_name FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $sender_name = $stmt->fetchColumn() ?: 'Customer';

                notifyAdmins(
                    "New message for #{$booking['reference_number']}",
                    "{$sender_name}: " . (strlen($message) > 50 ? substr($message, 0, 47) . '...' : $message),
                    'info',
                    "messages.php?booking_id=" . $booking_id
                );
            }
        }
    } catch (Exception $e) {
        error_log("Chat notification error: " . $e->getMessage());
    }

    echo json_encode(['success' => true, 'message_id' => $message_id]);
} else {
    http_response_code(405);
}
?>
