<?php
require '../config/db.php';
require '../config/function/function.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submitShipping'])) {
    $request_Id = date("YmdHis") . rand(1000, 9999);
    $dname       = cleanInput($_POST['dname']);
    $dphone      = cleanInput($_POST['dphone']);
    $departure   = cleanInput($_POST['depature']);
    $destination = cleanInput($_POST['destination']);
    $dweight     = cleanInput($_POST['dweight']);
    $type        = cleanInput($_POST['type']);
    $demail      = cleanInput($_POST['demail']);
    $dmessage    = cleanInput($_POST['dmessage']);
    $url = $_SERVER['HTTP_REFERER'];
    
    if (empty($dname) || empty($dphone) || empty($departure) || empty($destination) || empty($dweight) || empty($type) || empty($demail) || empty($dmessage)) {
        redirectWithMessage($url, "Please fill in all fields", "error");
        exit();
    }

    if (!filter_var($demail, FILTER_VALIDATE_EMAIL)) {
        redirectWithMessage($url, "Invalid email format", "error");
        exit();
    }

    if (!preg_match('/^\+?\d{10,15}$/', $dphone)) { 
        redirectWithMessage($url, "Invalid phone number format", "error");
        exit();
    }

    $query = "INSERT INTO ship (request_Id, dname, dphone, depature, destination, dweight, type, demail, dmessage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param("sssssssss", $request_Id, $dname, $dphone, $departure, $destination, $dweight, $type, $demail, $dmessage);
        
        if ($stmt->execute()) {
            redirectWithMessage('../success', "Booking successful", "success");
        } else {
            redirectWithMessage($url, "Failed to book. Please try again.", "error");
        }

        $stmt->close();
    } else {
        redirectWithMessage($url, "Database error. Please try again.", "error");
    }

    $conn->close();
    exit();
}