<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/guest.php'; 

session_start();
date_default_timezone_set('Asia/Bangkok');

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

$guest = new Guest($db);

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

$guest->id = isset($_POST['id']) ? $_POST['id'] : null;
$guest->guest_name = isset($_POST['guest_name']) ? $_POST['guest_name'] : null;
$guest->contact_number = isset($_POST['contact_number']) ? $_POST['contact_number'] : null;
$guest->email = isset($_POST['email']) ? $_POST['email'] : null;
$guest->country = isset($_POST['country']) ? $_POST['country'] : null;
$guest->ppnrc = isset($_POST['ppnrc']) ? $_POST['ppnrc'] : null;
$guest->address = isset($_POST['address']) ? $_POST['address'] : null;
$guest->entry_by = isset($_SESSION['user']) ? $_SESSION['user'] : "";
$guest->update_by = isset($_SESSION['user']) ? $_SESSION['user'] : "";

// Handle photo upload
$photoUrl = '';
if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
    $photo = $_FILES['photo'];
    $photoName = time() . "_" . basename($photo['name']);
    $photoPath = "upload/" . $photoName;

    // Check if the uploads directory exists and create it if not
    if (!is_dir('upload')) {
        mkdir('upload', 0755, true);
    }

    // Move the uploaded file to the desired folder
    if (move_uploaded_file($photo['tmp_name'], $photoPath)) {
        $photoUrl = $photoPath; // Use the path of the uploaded photo
    } else {
        echo json_encode(array("message" => "photo_error"));
        exit;
    }
}
$guest->photo = $photoUrl;
// Update the guest with the photo URL (if available)
// if ($data->id) {
//     $guest->photo_url = $photoUrl; // Add photo URL to the update operation
//     if ($guest->update()) {
//         echo json_encode(array("message" => "updated"));
//     } else {
//         echo json_encode(array("message" => "error"));
//     }
// } else {
    if ($guest->exist()) {
        echo json_encode(array("message" => "duplicate"));
    } elseif ($guest->create()) { // Pass photo URL to create method
        echo json_encode(array("message" => "created", "guest_id" => $guest->id));
    } else {
        echo json_encode(array("message" => "error"));
    }
// }
?>
