<?php
/**
 * Reservation Handler
 * Process room reservations
 */

header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/mailer.php';

function reservationFormatDate(string $date): string
{
    $ts = strtotime($date);
    return $ts ? date('F j, Y', $ts) : $date;
}

function reservationBuildEmailBody(array $data): string
{
    $guestName = htmlspecialchars((string)($data['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
    $bookingId = htmlspecialchars((string)($data['booking_id'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $roomType = htmlspecialchars((string)($data['room_type'] ?? 'Room'), ENT_QUOTES, 'UTF-8');
    $checkIn = htmlspecialchars((string)($data['check_in'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $checkOut = htmlspecialchars((string)($data['check_out'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $guests = htmlspecialchars((string)($data['guests'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $total = htmlspecialchars((string)($data['total'] ?? '0.00'), ENT_QUOTES, 'UTF-8');
    $phone = htmlspecialchars((string)($data['phone'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $specialRequests = trim((string)($data['special_requests'] ?? ''));
    $specialRequests = $specialRequests !== '' ? htmlspecialchars($specialRequests, ENT_QUOTES, 'UTF-8') : 'None';

    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; color: #1f2937; background:#f5f7fb; margin:0; padding:24px;">
    <div style="max-width:680px; margin:0 auto; background:#fff; border:1px solid #dbe5ef; border-radius:12px; overflow:hidden;">
        <div style="padding:20px 24px; background:#0f2942; color:#fff;">
            <h2 style="margin:0;">Zemaraim Room Reservation Confirmation</h2>
        </div>
        <div style="padding:22px 24px;">
            <p>Hello {$guestName}, your reservation is confirmed.</p>
            <table style="width:100%; border-collapse:collapse;">
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Booking ID</td><td style="padding:8px 0;">#{$bookingId}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Room</td><td style="padding:8px 0;">{$roomType}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Check In</td><td style="padding:8px 0;">{$checkIn}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Check Out</td><td style="padding:8px 0;">{$checkOut}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Guests</td><td style="padding:8px 0;">{$guests}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Phone</td><td style="padding:8px 0;">{$phone}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Special Requests</td><td style="padding:8px 0;">{$specialRequests}</td></tr>
            </table>
            <p style="margin-top:12px; padding:12px 14px; border:1px solid #cfe0f3; border-radius:10px; background:#f3f8fe;">
                <strong>Total Cost:</strong> \${$total}
            </p>
        </div>
    </div>
</body>
</html>
HTML;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$response = ['success' => false, 'message' => '', 'reservation_id' => null];

try {
    // Check if user is logged in
    if (!isLoggedIn()) {
        throw new Exception('Please login to make a reservation');
    }

    $user_id = getCurrentUserId();
    $room_id = isset($_POST['room_id']) ? (int)$_POST['room_id'] : 0;
    $check_in = trim($_POST['check_in'] ?? '');
    $check_out = trim($_POST['check_out'] ?? '');
    $number_of_guests = isset($_POST['guests']) ? (int)$_POST['guests'] : 1;
    $special_requests = trim($_POST['special_requests'] ?? '');

    // Validation
    if (!$room_id) {
        throw new Exception('Invalid room selected');
    }

    if (!strtotime($check_in)) {
        throw new Exception('Invalid check-in date');
    }

    if (!strtotime($check_out)) {
        throw new Exception('Invalid check-out date');
    }

    if (strtotime($check_out) <= strtotime($check_in)) {
        throw new Exception('Check-out date must be after check-in date');
    }

    if ($number_of_guests < 1) {
        throw new Exception('At least 1 guest required');
    }

    // Get room details
    $room_sql = "SELECT * FROM rooms WHERE id = ? AND is_available = 1";
    $room_stmt = $conn->prepare($room_sql);
    $room_stmt->bind_param('i', $room_id);
    $room_stmt->execute();
    $room_result = $room_stmt->get_result();

    if ($room_result->num_rows === 0) {
        throw new Exception('Room not available');
    }

    $room = $room_result->fetch_assoc();

    if ($number_of_guests > $room['max_guests']) {
        throw new Exception('Too many guests for selected room');
    }

    // Calculate total price
    $check_in_time = strtotime($check_in);
    $check_out_time = strtotime($check_out);
    $days = ($check_out_time - $check_in_time) / (60 * 60 * 24);
    $total_price = $room['price_per_night'] * $days;

    // Insert reservation
    $res_sql = "INSERT INTO reservations (user_id, room_id, check_in_date, check_out_date, number_of_guests, total_price, special_requests, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')";
    $res_stmt = $conn->prepare($res_sql);

    if (!$res_stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $res_stmt->bind_param('iisssds', $user_id, $room_id, $check_in, $check_out, $number_of_guests, $total_price, $special_requests);

    if ($res_stmt->execute()) {
        $reservation_id = $res_stmt->insert_id;
        $res_stmt->close();

        $userName = 'Guest';
        $userEmail = '';
        $userPhone = '';
        $userStmt = $conn->prepare("SELECT first_name, last_name, email, phone FROM users WHERE id = ? LIMIT 1");
        if ($userStmt) {
            $userStmt->bind_param('i', $user_id);
            $userStmt->execute();
            $userResult = $userStmt->get_result();
            $userRow = $userResult ? $userResult->fetch_assoc() : null;
            $userStmt->close();

            if ($userRow) {
                $fullName = trim((string)($userRow['first_name'] ?? '') . ' ' . (string)($userRow['last_name'] ?? ''));
                $userName = $fullName !== '' ? $fullName : 'Guest';
                $userEmail = trim((string)($userRow['email'] ?? ''));
                $userPhone = trim((string)($userRow['phone'] ?? ''));
            }
        }

        $emailSent = false;
        if ($userEmail !== '') {
            $emailBody = reservationBuildEmailBody([
                'guest_name' => $userName,
                'booking_id' => (string)$reservation_id,
                'room_type' => (string)($room['room_type'] ?? 'Room'),
                'check_in' => reservationFormatDate($check_in),
                'check_out' => reservationFormatDate($check_out),
                'guests' => (string)$number_of_guests,
                'phone' => $userPhone !== '' ? $userPhone : '-',
                'special_requests' => $special_requests,
                'total' => number_format($total_price, 2),
            ]);
            $emailSent = sendEmail($userEmail, $userName, 'Your Zemaraim Room Reservation Confirmation', $emailBody);
        }
        
        $response['success'] = true;
        $response['message'] = $emailSent
            ? 'Reservation created successfully!'
            : 'Reservation created successfully. Confirmation email could not be sent.';
        $response['reservation_id'] = $reservation_id;
        $response['total_price'] = number_format($total_price, 2);
        $response['email_sent'] = $emailSent;
        $response['redirect'] = 'reservation.php?id=' . $reservation_id;
    } else {
        throw new Exception('Failed to create reservation');
    }

} catch (Exception $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
