<?php
require_once '../config/headers.php';
require_once '../config/constants.php';
require_once '../config/database.php';
require_once '../utils/response.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../phpmailer/src/Exception.php';
require '../phpmailer/src/PHPMailer.php';
require '../phpmailer/src/SMTP.php';

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

$data = json_decode(file_get_contents("php://input"));

if (empty($data->id) || empty($data->status)) {
    sendResponse(400, 'error', 'ID and status are required');
}

// Convert "Approved" to "approved" for DB ENUM
$new_status = strtolower($data->status);
$valid_statuses = ['pending', 'approved', 'rejected'];

if (!in_array($new_status, $valid_statuses)) {
    sendResponse(400, 'error', 'Invalid status');
}

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

try {
    // Fetch hotel details first for the email
    $stmtFetch = $db->prepare("SELECT email, owner_name, hotel_name, status FROM hotel_registrations WHERE id = :id LIMIT 1");
    $stmtFetch->execute([':id' => $data->id]);
    
    if ($stmtFetch->rowCount() === 0) {
        sendResponse(404, 'error', 'Registration not found');
    }
    
    $hotel = $stmtFetch->fetch(PDO::FETCH_ASSOC);

    // Update status
    $stmtUpdate = $db->prepare("UPDATE hotel_registrations SET status = :status WHERE id = :id");
    $stmtUpdate->execute([':status' => $new_status, ':id' => $data->id]);

    $emailSent = false;

    // Send Email Notification if Approved or Rejected
    if ($new_status === 'approved' || $new_status === 'rejected') {
        $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;                                    

            $mail->setFrom(SMTP_FROM_EMAIL, 'HR Trips Partners');
            $mail->addAddress($hotel['email'], $hotel['owner_name']);

            $mail->isHTML(true);

            if ($new_status === 'approved') {
                $mail->Subject = "Hotel Partner Account Approved - HR Trips";
                $mail->Body = "
                <div style='font-family: Arial, sans-serif; padding: 20px;'>
                    <h2 style='color: #16a34a;'>Congratulations! 🎉</h2>
                    <p>Dear {$hotel['owner_name']},</p>
                    <p>Your hotel registration for <strong>{$hotel['hotel_name']}</strong> has been approved!</p>
                    <p>You can now log in to the Hotel Owner Dashboard using your registered email and password to start adding your rooms and prices.</p>
                    <br>
                    <a href='https://hrtrips.com/hotel-owner/login' style='background: #1e40af; color: #ffffff; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;'>Go to Dashboard</a>
                    <br><br>
                    <p>Welcome aboard!<br>The HR Trips Team</p>
                </div>";
            } else {
                $mail->Subject = "Hotel Registration Update - HR Trips";
                $mail->Body = "
                <div style='font-family: Arial, sans-serif; padding: 20px;'>
                    <h2 style='color: #dc2626;'>Application Update</h2>
                    <p>Dear {$hotel['owner_name']},</p>
                    <p>We regret to inform you that your registration for <strong>{$hotel['hotel_name']}</strong> has been declined at this time.</p>
                    <p>If you believe this was an error or wish to provide additional documentation, please reply to this email.</p>
                    <br>
                    <p>Regards,<br>The HR Trips Team</p>
                </div>";
            }

            $mail->send();
            $emailSent = true;
        } catch (Exception $e) {
            error_log("Approval Email Failed: " . $mail->ErrorInfo);
        }
    }

    sendResponse(200, 'success', 'Status updated successfully');

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