<?php
require_once "config.php";

$response = ["success" => false, "message" => "Something went wrong"];

if($_SERVER["REQUEST_METHOD"] === "POST"){
    $name = $_POST['visitor_name'] ?? '';
    $purpose = $_POST['purpose'] ?? '';
    $mobile = $_POST['mobile'] ?? '';

    $otp = rand(100000, 999999);

    $uploadDir = "uploads/";
    if(!is_dir($uploadDir)) mkdir($uploadDir);

    $photoPath = null;
    if(isset($_FILES['photo'])){
        $photoName = "photo_".time()."_".basename($_FILES['photo']['name']);
        move_uploaded_file($_FILES['photo']['tmp_name'], $uploadDir.$photoName);
        $photoPath = $uploadDir.$photoName;
    }

    $docPath = null;
    if(isset($_FILES['document'])){
        $docName = "doc_".time()."_".basename($_FILES['document']['name']);
        move_uploaded_file($_FILES['document']['tmp_name'], $uploadDir.$docName);
        $docPath = $uploadDir.$docName;
    }

    $stmt = $pdo->prepare("INSERT INTO gate_enquiries (visitor_name, purpose, mobile, photo_path, document_path, otp) VALUES (?,?,?,?,?,?)");
    if($stmt->execute([$name, $purpose, $mobile, $photoPath, $docPath, $otp])){
        // TODO: integrate SMS API to send OTP to mobile
        $response = ["success"=>true, "message"=>"OTP sent to mobile!", "enquiry_id"=>$pdo->lastInsertId()];
    } else {
        $response = ["success"=>false, "message"=>"Error saving enquiry"];
    }
}

echo json_encode($response);
