<?php
session_start();
include "../config/db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['order_id'])) {
    $order_id = mysqli_real_escape_string($conn, $_POST['order_id']);
    $pickup_date = mysqli_real_escape_string($conn, $_POST['pickup_date']);
    $instructions = mysqli_real_escape_string($conn, $_POST['instructions']);
    $user_id = $_SESSION['user_id'];

    // Verify order belongs to user
    $check = mysqli_query($conn, "SELECT id FROM orders WHERE id = '$order_id' AND user_id = '$user_id'");
    if (mysqli_num_rows($check) > 0) {
        // Update order with pickup info
        $sql = "UPDATE orders SET 
                status = 'Return Requested', 
                pickup_scheduled_date = '$pickup_date',
                special_instructions = CONCAT(IFNULL(special_instructions, ''), '\nPickup Instructions: ', '$instructions')
                WHERE id = '$order_id'";
        
        if (mysqli_query($conn, $sql)) {
            // Add notification for admin
            $notif_title = "New Pickup Scheduled - Order #$order_id";
            $notif_msg = "User " . $_SESSION['user_name'] . " scheduled a pickup for $pickup_date.";
            mysqli_query($conn, "INSERT INTO admin_notifications (title, message, type) VALUES ('$notif_title', '$notif_msg', 'pickup')");
            
            $_SESSION['success_msg'] = "Pickup scheduled successfully for $pickup_date!";
        } else {
            $_SESSION['error_msg'] = "Something went wrong. Please try again.";
        }
    } else {
        $_SESSION['error_msg'] = "Invalid order.";
    }
}

header("Location: my-rentals.php");
exit();
?>
