<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['pickup_id'])) {
    header('Location: pickup_requests.php');
    exit;
}

$pickup_id = intval($_POST['pickup_id']);

// Fetch the pickup request
$stmt = $pdo->prepare("SELECT * FROM pickup_requests WHERE id = ?");
$stmt->execute([$pickup_id]);
$pickup = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$pickup) {
    die("Pickup request not found.");
}

// Insert bill header
$stmt = $pdo->prepare("INSERT INTO bills (user_name, user_tp, user_address, total_amount, created_at) VALUES (?, ?, ?, ?, NOW())");
$stmt->execute([
    $pickup['user_name'],
    $pickup['user_tp'],
    $pickup['user_address'],
    $pickup['grand_total'],
]);
$bill_id = $pdo->lastInsertId();

// Decode jobs from items_json
$jobs = json_decode($pickup['items_json'], true);

if (!is_array($jobs)) {
    die("Invalid items data in pickup request.");
}

// Insert jobs for this bill
$jobInsertStmt = $pdo->prepare("INSERT INTO bill_jobs (bill_id, job_type_id, job_name, rate, quantity, total) VALUES (?, ?, ?, ?, ?, ?)");

foreach ($jobs as $job) {
    // Validate required fields
    if (!isset($job['job_type_id'], $job['name'], $job['rate'], $job['qty'], $job['total'])) {
        continue; // skip invalid job entry
    }

    $jobInsertStmt->execute([
        $bill_id,
        $job['job_type_id'],
        $job['name'],
        $job['rate'],
        $job['qty'],
        $job['total'],
    ]);
}

// Redirect back with success message
header('Location: pickup_requests.php?created_bill_id=' . $bill_id);
exit;
