<?php
// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set content type
header('Content-Type: application/json');

// Allow CORS if needed
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

// Validate and sanitize input data
function sanitize_input($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

// Get form data
$firstName = sanitize_input($_POST['firstName'] ?? '');
$lastName = sanitize_input($_POST['lastName'] ?? '');
$email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
$phone = sanitize_input($_POST['phone'] ?? '');
$checkin = sanitize_input($_POST['checkin'] ?? '');
$checkout = sanitize_input($_POST['checkout'] ?? '');
$guests = sanitize_input($_POST['guests'] ?? '');
$rooms = sanitize_input($_POST['rooms'] ?? '');
$requests = sanitize_input($_POST['requests'] ?? '');

// Validate required fields
$errors = [];
if (empty($firstName)) $errors[] = 'First name is required';
if (empty($lastName)) $errors[] = 'Last name is required';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required';
if (empty($phone)) $errors[] = 'Phone number is required';
if (empty($checkin)) $errors[] = 'Check-in date is required';
if (empty($checkout)) $errors[] = 'Check-out date is required';
if (empty($guests)) $errors[] = 'Number of guests is required';
if (empty($rooms)) $errors[] = 'Number of rooms is required';

// Validate dates
if (!empty($checkin) && !empty($checkout)) {
    $checkinDate = DateTime::createFromFormat('Y-m-d', $checkin);
    $checkoutDate = DateTime::createFromFormat('Y-m-d', $checkout);
    $today = new DateTime();
    
    if (!$checkinDate || $checkinDate < $today) {
        $errors[] = 'Check-in date must be today or later';
    }
    
    if (!$checkoutDate || $checkoutDate <= $checkinDate) {
        $errors[] = 'Check-out date must be after check-in date';
    }
}

// reCAPTCHA validation (optional - requires Google reCAPTCHA keys)
/*
if (isset($_POST['g-recaptcha-response'])) {
    $recaptcha_secret = 'YOUR_SECRET_KEY_HERE';
    $recaptcha_response = $_POST['g-recaptcha-response'];
    
    $verify_response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$recaptcha_secret.'&response='.$recaptcha_response);
    $response_data = json_decode($verify_response);
    
    if (!$response_data->success) {
        $errors[] = 'Please complete the reCAPTCHA verification';
    }
}
*/

// If there are validation errors, return them
if (!empty($errors)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => implode(', ', $errors)]);
    exit;
}

// Calculate number of nights
$checkinDate = new DateTime($checkin);
$checkoutDate = new DateTime($checkout);
$nights = $checkinDate->diff($checkoutDate)->days;
$totalCost = $nights * $rooms * 35000; // TSh 35,000 per room per night

// Prepare email content
$to = 'bookings@londonhotel.co.tz';
$subject = 'New Booking Request - London Hotel';
$from = 'bookingform@londonhotel.co.tz';

// Create HTML email content
$message = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background-color: #ffc107; color: #000; padding: 20px; text-align: center; }
        .content { background-color: #f9f9f9; padding: 20px; }
        .booking-details { background-color: #fff; padding: 15px; margin: 10px 0; border-left: 4px solid #ffc107; }
        .footer { background-color: #333; color: #fff; padding: 15px; text-align: center; }
        .label { font-weight: bold; color: #555; }
        .value { margin-bottom: 10px; }
        .total { background-color: #ffc107; padding: 10px; font-weight: bold; text-align: center; margin: 15px 0; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>🏨 New Booking Request</h1>
            <p>London Hotel - Dar es Salaam</p>
        </div>
        
        <div class='content'>
            <h2>Guest Information</h2>
            <div class='booking-details'>
                <div class='value'><span class='label'>Name:</span> {$firstName} {$lastName}</div>
                <div class='value'><span class='label'>Email:</span> {$email}</div>
                <div class='value'><span class='label'>Phone:</span> {$phone}</div>
            </div>
            
            <h2>Booking Details</h2>
            <div class='booking-details'>
                <div class='value'><span class='label'>Check-in Date:</span> {$checkin}</div>
                <div class='value'><span class='label'>Check-out Date:</span> {$checkout}</div>
                <div class='value'><span class='label'>Number of Nights:</span> {$nights}</div>
                <div class='value'><span class='label'>Number of Guests:</span> {$guests}</div>
                <div class='value'><span class='label'>Number of Rooms:</span> {$rooms}</div>
            </div>
            
            <div class='total'>
                Estimated Total: TSh " . number_format($totalCost) . " ({$nights} nights × {$rooms} rooms × TSh 35,000)
            </div>";

if (!empty($requests)) {
    $message .= "
            <h2>Special Requests</h2>
            <div class='booking-details'>
                <p>{$requests}</p>
            </div>";
}

$message .= "
            <p><strong>Next Steps:</strong></p>
            <ul>
                <li>Contact the guest within 24 hours to confirm availability</li>
                <li>Discuss payment arrangements and policies</li>
                <li>Send booking confirmation with check-in instructions</li>
            </ul>
        </div>
        
        <div class='footer'>
            <p>London Hotel | Ubungo Maziwa, Dar es Salaam | +255 658 855268</p>
            <p>This booking request was submitted on " . date('Y-m-d H:i:s') . "</p>
        </div>
    </div>
</body>
</html>";

// Email headers
$headers = [
    'From: ' . $from,
    'Reply-To: ' . $email,
    'MIME-Version: 1.0',
    'Content-Type: text/html; charset=UTF-8',
    'X-Mailer: PHP/' . phpversion()
];

// Send email
$mail_sent = mail($to, $subject, $message, implode("\r\n", $headers));

if ($mail_sent) {
    // Log successful booking (optional)
    $log_entry = date('Y-m-d H:i:s') . " - Booking request from {$firstName} {$lastName} ({$email}) for {$checkin} to {$checkout}\n";
    file_put_contents('booking_logs.txt', $log_entry, FILE_APPEND | LOCK_EX);
    
    echo json_encode([
        'success' => true, 
        'message' => 'Booking request sent successfully! We will contact you within 24 hours.',
        'redirect' => 'booking-success.html'
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Sorry, there was an error sending your booking request. Please try again or contact us directly at +255 658 855268.'
    ]);
}
?>

