<?php
require_once '../config/headers.php';
require_once '../config/constants.php'; // Required for SMTP settings
require_once '../config/database.php';
require_once '../utils/response.php';

// Import PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer files
require '../phpmailer/src/Exception.php';
require '../phpmailer/src/PHPMailer.php';
require '../phpmailer/src/SMTP.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

// 1. Validate required text fields from $_POST
if (empty($_POST['email']) || empty($_POST['password']) || empty($_POST['hotelName'])) {
    sendResponse(400, 'error', 'Missing required fields');
}

$database = new Database();
$db = $database->getConnection();

try {
    // 2. Check if email already exists
    $checkStmt = $db->prepare("SELECT id FROM hotel_registrations WHERE email = :email LIMIT 1");
    $checkStmt->execute([':email' => $_POST['email']]);
    if ($checkStmt->rowCount() > 0) {
        sendResponse(400, 'error', 'Email is already registered. Please login or use a different email.');
    }

    // 3. Hash the password
    $hashed_password = password_hash($_POST['password'], PASSWORD_BCRYPT);

    // 4. Setup File Upload Directory
    $uploadDir = '../uploads/hotels/';
    // Base URL to access the images (Update this to match your actual server domain/path)
    $baseUrl = '/api/uploads/hotels/'; 
    
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    // 5. Helper Function to Process Multiple Files
    function uploadFiles($fileInputName, $uploadDir, $baseUrl) {
        $uploadedUrls = [];
        if (isset($_FILES[$fileInputName]) && is_array($_FILES[$fileInputName]['name'])) {
            $fileCount = count($_FILES[$fileInputName]['name']);
            
            for ($i = 0; $i < $fileCount; $i++) {
                if ($_FILES[$fileInputName]['error'][$i] === UPLOAD_ERR_OK) {
                    $tmpName = $_FILES[$fileInputName]['tmp_name'][$i];
                    $originalName = basename($_FILES[$fileInputName]['name'][$i]);
                    
                    // Create a unique filename to prevent overwriting
                    $extension = pathinfo($originalName, PATHINFO_EXTENSION);
                    $uniqueName = uniqid() . '_' . time() . '.' . $extension;
                    $destination = $uploadDir . $uniqueName;

                    if (move_uploaded_file($tmpName, $destination)) {
                        $uploadedUrls[] = $baseUrl . $uniqueName;
                    }
                }
            }
        }
        return $uploadedUrls;
    }

    // 6. Process File Uploads for all categories
    $roomPicsUrls = uploadFiles('roomPics', $uploadDir, $baseUrl);
    $receptionPicsUrls = uploadFiles('receptionPics', $uploadDir, $baseUrl);
    $bathroomPicsUrls = uploadFiles('bathroomPics', $uploadDir, $baseUrl);
    $interiorPicsUrls = uploadFiles('interiorExteriorPics', $uploadDir, $baseUrl);

    // 7. Insert into Database
    $query = "INSERT INTO hotel_registrations (
        owner_name, owner_contact, property_manager_name, property_manager_phone, 
        email, password_hash, hotel_name, gst_number, registration_number, 
        fire_safety_noc, cctv_camera, bank_details, location_link, 
        hotel_address, city, state, pincode, 
        room_pics, reception_pics, bathroom_pics, interior_exterior_pics
    ) VALUES (
        :owner_name, :owner_contact, :pm_name, :pm_phone, 
        :email, :password_hash, :hotel_name, :gst, :reg_num, 
        :fire_noc, :cctv, :bank, :location, 
        :address, :city, :state, :pincode, 
        :room_pics, :reception_pics, :bathroom_pics, :interior_pics
    )";

    $stmt = $db->prepare($query);

    $stmt->execute([
        ':owner_name'    => $_POST['ownerName'],
        ':owner_contact' => $_POST['ownerContact'],
        ':pm_name'       => $_POST['propertyManagerName'],
        ':pm_phone'      => $_POST['propertyManagerPhone'],
        ':email'         => $_POST['email'],
        ':password_hash' => $hashed_password,
        ':hotel_name'    => $_POST['hotelName'],
        ':gst'           => $_POST['gst'],
        ':reg_num'       => $_POST['hotelRegistrationNumber'],
        ':fire_noc'      => $_POST['fireSafetyNoc'],
        ':cctv'          => $_POST['cctvCamera'],
        ':bank'          => $_POST['bankDetails'],
        ':location'      => $_POST['location'],
        ':address'       => $_POST['hotelAddress'],
        ':city'          => $_POST['city'],
        ':state'         => $_POST['state'],
        ':pincode'       => $_POST['pincode'],
        
        // Encode the arrays of URLs into JSON strings for the database
        ':room_pics'      => json_encode($roomPicsUrls),
        ':reception_pics' => json_encode($receptionPicsUrls),
        ':bathroom_pics'  => json_encode($bathroomPicsUrls),
        ':interior_pics'  => json_encode($interiorPicsUrls)
    ]);

    $registrationId = $db->lastInsertId();

    // 8. Send the Confirmation Email using PHPMailer
    $emailSent = false;
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();                                            
        $mail->Host       = SMTP_HOST;                     
        $mail->SMTPAuth   = true;                                   
        $mail->Username   = SMTP_USER;                     
        $mail->Password   = SMTP_PASS;                               
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            
        $mail->Port       = SMTP_PORT;                                    

        // Set sender and recipient
        $mail->setFrom(SMTP_FROM_EMAIL, 'HR Trips Partner Support');
        $mail->addAddress($_POST['email'], $_POST['ownerName']);
        
        // Send a copy to the admin so you know a new hotel applied
        $mail->addBCC(SMTP_FROM_EMAIL); 

        $mail->isHTML(true);
        $mail->Subject = "Hotel Registration Received - HR Trips";
        
        // HTML Email Template
        $mail->Body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e2e8f0; border-radius: 10px; overflow: hidden;'>
            <div style='background-color: #0f172a; padding: 20px; text-align: center;'>
                <h1 style='color: #ffffff; margin: 0; font-size: 24px;'>Application Received</h1>
            </div>
            <div style='padding: 30px; background-color: #ffffff;'>
                <p style='font-size: 16px; color: #334155;'>Dear <strong>{$_POST['ownerName']}</strong>,</p>
                <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                    Thank you for applying to partner with HR Trips! We have successfully received the registration details for <strong>{$_POST['hotelName']}</strong>.
                </p>
                
                <div style='background-color: #fffbeb; padding: 15px; border: 1px dashed #f59e0b; border-radius: 8px; text-align: center; color: #b45309; font-weight: bold; margin: 20px 0;'>
                    Status: UNDER REVIEW
                </div>

                <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                    <strong>What happens next?</strong><br>
                    Our administrative team is currently reviewing your submitted documents and hotel details. This process usually takes 24-48 hours. 
                </p>
                <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                    Once your account is approved, we will send you another email notifying you that your account is active. You will then be able to log into the Owner Dashboard using this email address and the password you created to start managing your bookings and packages.
                </p>
                
                <hr style='border: none; border-top: 1px solid #e2e8f0; margin: 30px 0;'>
                <p style='font-size: 14px; color: #94a3b8; margin: 0;'>
                    Best Regards,<br>
                    <strong>The HR Trips Partner Team</strong><br>
                    Need help? Call us at 7992481351
                </p>
            </div>
        </div>";

        $mail->send();
        $emailSent = true;
    } catch (Exception $e) {
        // Log the error but don't stop the script (the database insert was already successful)
        error_log("Hotel Registration Email failed to send. Mailer Error: {$mail->ErrorInfo}");
    }

    sendResponse(201, 'success', 'Hotel registered successfully. ' . ($emailSent ? 'Confirmation email sent.' : 'Email failed to send.'));

} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>