<?php 
session_start();
require_once('database/DBController.php'); 

$db = new DBController();
$conn = $db->con; 

if (!isset($_SESSION['login'])) {
    echo "<p class='error-msg'>You need to log in first.</p>";
    exit();
}

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Store orderId and orderAmount in session for security
    $_SESSION['orderId'] = $_POST['orderId'];
    $_SESSION['orderAmount'] = $_POST['orderAmount'];

    // Sanitize inputs
    $full_name = htmlspecialchars(trim($_POST['full_name'] ?? ""));
    $phone = htmlspecialchars(trim($_POST['phone'] ?? ""));
    $pincode = htmlspecialchars(trim($_POST['pincode'] ?? ""));
    $state = htmlspecialchars(trim($_POST['state'] ?? ""));
    $city = htmlspecialchars(trim($_POST['city'] ?? ""));
    $house_no = htmlspecialchars(trim($_POST['house_no'] ?? ""));
    $road_name = htmlspecialchars(trim($_POST['road_name'] ?? ""));
    $address_type = htmlspecialchars(trim($_POST['address_type'] ?? ""));

    // Validate required fields
    if (empty($full_name) || empty($phone) || empty($pincode) || empty($state) || empty($city) || empty($house_no) || empty($road_name) || empty($address_type)) {
        echo "<p class='error-msg'>All fields are required.</p>";
    } else {
        // Insert Address
        $sql = "INSERT INTO user_addresses (user_id, full_name, phone, pincode, state, city, house_no, road_name, address_type) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("issssssss", $user_id, $full_name, $phone, $pincode, $state, $city, $house_no, $road_name, $address_type);
        
        if ($stmt->execute()) {
            // Redirect to payment.php after successful insertion
            header("Location: request.php");
            exit(); 
        } else {
            echo "<p class='error-msg'>Error saving address: " . $conn->error . "</p>";
        }
        $stmt->close();
    }
}
?>
