<?php
require_once __DIR__ . '/../include/db.php';
session_start();
if (!isset($_SESSION['delivery_man_id'])) { header("Location: dashboard.php"); exit; }

$order_id = intval($_POST['order_id']);
$deliver_now = intval($_POST['deliver_now']);
$challan_number = $conn->real_escape_string(trim($_POST['challan_number']));
$remarks = $conn->real_escape_string(trim($_POST['remarks']));
$delivery_man_id = intval($_SESSION['delivery_man_id']);

if ($order_id <= 0 || $deliver_now <= 0) { die("Invalid input"); }

// calc available for this delivery_man & order
$q = $conn->prepare("
    SELECT IFNULL(SUM(assigned_qty),0) AS assigned, IFNULL(SUM(delivered_qty),0) AS delivered
    FROM delivery_assignments
    WHERE order_id = ? AND delivery_man_id = ?
");
$q->bind_param("ii", $order_id, $delivery_man_id);
$q->execute();
$summary = $q->get_result()->fetch_assoc();
$assigned = intval($summary['assigned']);
$delivered = intval($summary['delivered']);
$available = $assigned - $delivered;
if ($available < 0) $available = 0;

if ($deliver_now > $available) { die("You cannot deliver more than available ($available)."); }

// handle challan image
$upload_path = __DIR__ . "/uploads/";
if (!is_dir($upload_path)) mkdir($upload_path, 0777, true);

$img_name = null;
if (!empty($_FILES['challan_image']['name'])) {
    $img_name = time() . "_" . preg_replace('/[^A-Za-z0-9._-]/', '_', basename($_FILES['challan_image']['name']));
    move_uploaded_file($_FILES['challan_image']['tmp_name'], $upload_path . $img_name);
}

// Update assignment rows for this order+delivery_man until deliver_now consumed
$need = $deliver_now;
$stmt_sel = $conn->prepare("SELECT id, assigned_qty, delivered_qty FROM delivery_assignments WHERE order_id = ? AND delivery_man_id = ? ORDER BY id ASC");
$stmt_sel->bind_param("ii", $order_id, $delivery_man_id);
$stmt_sel->execute();
$res = $stmt_sel->get_result();

while ($need > 0 && $row = $res->fetch_assoc()) {
    $aid = intval($row['id']);
    $assigned_qty = intval($row['assigned_qty']);
    $was_del = intval($row['delivered_qty']);
    $rem = $assigned_qty - $was_del;
    if ($rem <= 0) continue;

    $take = ($rem >= $need) ? $need : $rem;
    $new_del = $was_del + $take;
    $new_status = ($new_del >= $assigned_qty) ? 'delivered' : 'partial';

    $u = $conn->prepare("UPDATE delivery_assignments SET delivered_qty = ?, status = ?, challan_number = ?, challan_image = ?, remarks = ? WHERE id = ?");
    $u->bind_param("issssi", $new_del, $new_status, $challan_number, $img_name, $remarks, $aid);
    $u->execute();

    $need -= $take;
}

// Recalculate totals and update orders.status based on order_measurements total
$s = $conn->prepare("
    SELECT IFNULL(SUM(assigned_qty),0) AS assigned, IFNULL(SUM(delivered_qty),0) AS delivered
    FROM delivery_assignments
    WHERE order_id = ?
");
$s->bind_param("i", $order_id);
$s->execute();
$sum = $s->get_result()->fetch_assoc();
$total_assigned = intval($sum['assigned']);
$total_delivered = intval($sum['delivered']);

$st = $conn->prepare("SELECT IFNULL(SUM(total_qty),0) AS total_order_qty FROM order_measurements WHERE order_id = ?");
$st->bind_param("i", $order_id);
$st->execute();
$stRow = $st->get_result()->fetch_assoc();
$order_total_qty = intval($stRow['total_order_qty']);

$new_status = ($total_delivered >= $order_total_qty && $order_total_qty>0) ? 'delivered' : (($total_delivered > 0) ? 'partial' : 'pending');
$u2 = $conn->prepare("UPDATE orders SET status = ? WHERE id = ?");
$u2->bind_param("si", $new_status, $order_id);
$u2->execute();

header("Location: dashboard.php?msg=ok");
exit;
