<?php
ini_set('display_errors', 0); // keep OFF in production
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

// Role check
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: bbu_list.php?error=Unauthorized access");
    exit();
}

// Get ID
$bbu_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($bbu_id <= 0) {
    header("Location: bbu_list.php?error=Invalid BBU ID");
    exit();
}

try {
    $conn->begin_transaction();

    // 🔹 Fetch BBU
    $stmt = $conn->prepare("
        SELECT id, bbu_no, status, project_id 
        FROM bbu_master 
        WHERE id = ?
    ");
    $stmt->bind_param("i", $bbu_id);
    $stmt->execute();
    $bbu = $stmt->get_result()->fetch_assoc();

    if (!$bbu) {
        throw new Exception("BBU not found");
    }

    // 🔹 Only Draft allowed
    if ($bbu['status'] !== 'Draft') {
        throw new Exception("Only Draft BBU can be deleted");
    }

    // 🔹 Fetch items
    $items_stmt = $conn->prepare("
        SELECT 
            bi.quantity,
            bi.serial_no,
            im.id AS item_id,
            pi.id AS project_inventory_id
        FROM bbu_items bi
        LEFT JOIN inventory_master im ON bi.model_no = im.model_no
        LEFT JOIN project_inventory pi 
            ON pi.project_id = ? AND pi.item_id = im.id
        WHERE bi.bbu_id = ?
    ");
    $items_stmt->bind_param("ii", $bbu['project_id'], $bbu_id);
    $items_stmt->execute();
    $items = $items_stmt->get_result();

    // 🔹 Prepare statements
    $update_stock = $conn->prepare("
        UPDATE project_inventory 
        SET current_stock = current_stock + ?, 
            last_updated = NOW()
        WHERE id = ?
    ");

    $update_serial = $conn->prepare("
        UPDATE project_inventory_serials 
        SET status = 'IN',
            issued_date = NULL,
            bbu_id = NULL,
            updated_at = NOW()
        WHERE serial_no = ? AND project_id = ? AND item_id = ?
    ");

    // 🔹 Restore stock & serials
    while ($item = $items->fetch_assoc()) {

        // Restore stock
        if (!empty($item['project_inventory_id'])) {
            $qty = (float)$item['quantity'];
            $update_stock->bind_param("di", $qty, $item['project_inventory_id']);
            $update_stock->execute();
        }

        // Restore serial numbers
        if (!empty($item['serial_no']) && !empty($item['item_id'])) {
            $serials = array_map('trim', explode(',', $item['serial_no']));

            foreach ($serials as $serial) {
                if ($serial !== '') {
                    $update_serial->bind_param(
                        "sii",
                        $serial,
                        $bbu['project_id'],
                        $item['item_id']
                    );
                    $update_serial->execute();
                }
            }
        }
    }

    // 🔹 Delete items
    $del_items = $conn->prepare("DELETE FROM bbu_items WHERE bbu_id = ?");
    $del_items->bind_param("i", $bbu_id);
    $del_items->execute();

    // 🔹 Delete main BBU
    $del_bbu = $conn->prepare("DELETE FROM bbu_master WHERE id = ?");
    $del_bbu->bind_param("i", $bbu_id);
    $del_bbu->execute();

    $conn->commit();

    // ✅ Success redirect (IMPORTANT)
    header("Location: bbu_list.php?success=" . urlencode("BBU #" . $bbu['bbu_no'] . " deleted successfully"));
    exit();

} catch (Exception $e) {

    $conn->rollback();
    error_log("BBU Delete Error: " . $e->getMessage());

    // ❌ Error redirect
    header("Location: bbu_list.php?error=" . urlencode($e->getMessage()));
    exit();
}

$conn->close();
?>