<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

ob_start();
session_start();
require_once '../includes/functions.php';
require_once '../includes/db.php';

requireLogin();

$isAdmin   = isAdmin();
$isManager = isManager();
$isCashier = isCashier();

$accessibleBranches = getAccessibleBranches($pdo);

if (count($accessibleBranches) === 1) {
    $branch_id = $accessibleBranches[0];
} else {
    $branch_id = isset($_GET['branch']) ? (int)$_GET['branch'] : 0;

    if (!in_array($branch_id, $accessibleBranches)) {
        $branch_id = 0;
    }
}

$message = '';

/* =========================================================
   PREFILL FROM PICKUP (IF PROVIDED)
========================================================= */

$prefill_contact = '';
$prefill_name    = '';

if (!empty($_GET['pickup_id'])) {

    $pickup_id = (int) $_GET['pickup_id'];

    $stmtPickupCheck = $pdo->prepare("
        SELECT pickup_id, user_tp, user_name
        FROM pickup
        WHERE pickup_id = ?
    ");
    $stmtPickupCheck->execute([$pickup_id]);
    $pickup = $stmtPickupCheck->fetch(PDO::FETCH_ASSOC);

    if (!$pickup) {
        die('Invalid pickup.');
    }

    $prefill_contact = $pickup['user_tp'];
    $prefill_name    = $pickup['user_name'];

    if (!preg_match('/^0\d{9}$/', $prefill_contact)) {
        $prefill_contact = '';
    }
}


/* =========================================================
   PREVIEW NEXT BILL NUMBER (SAFE, NO LOCK)
   ========================================================= */
$stmtPreview = $pdo->prepare(
    "SELECT last_number FROM branch_sequences WHERE branch_id = ?"
);
$stmtPreview->execute([$branch_id]);
$previewLast = $stmtPreview->fetchColumn();

$previewNumber = '';

if ($branch_id > 0) {

    $stmtPreview = $pdo->prepare(
        "SELECT last_number FROM branch_sequences WHERE branch_id = ?"
    );
    $stmtPreview->execute([$branch_id]);
    $previewLast = $stmtPreview->fetchColumn();

    if ($previewLast !== false) {

        $previewNext = ((int)$previewLast) + 1;

        if ($branch_id == 2) {
            $numericPart = str_pad($previewNext, 5, '0', STR_PAD_LEFT);
        } else {
            $numericPart = $previewNext;
        }

        $previewNumber = $branch_id . '-' . $numericPart;
    }
}


/* =========================================================
   HANDLE FORM SUBMISSION
   ========================================================= */
if ($_SERVER["REQUEST_METHOD"] === "POST") {

if ($branch_id <= 0) {
    $message = "Please select a branch.";
}

    $contact = trim($_POST['customer_contact'] ?? '');
    $name    = trim($_POST['customer_name'] ?? '');
    $in_date = $_POST['in_date'] ?? date('Y-m-d');

    if (!preg_match('/^0[0-9]{9}$/', $contact)) {
        $message = "Invalid phone number. Must be 10 digits starting with 0.";
    } else {

        try {
            $pdo->beginTransaction();

            /* 1. Get or Create Customer (Shared Across Branches) */
            $stmt = $pdo->prepare(
                "SELECT customer_id FROM customers WHERE contact_number = ?"
            );
            $stmt->execute([$contact]);
            $customer_id = $stmt->fetchColumn();

            if (!$customer_id) {
                $stmtInsertCustomer = $pdo->prepare(
                    "INSERT INTO customers (name, contact_number) VALUES (?, ?)"
                );
                $stmtInsertCustomer->execute([$name, $contact]);
                $customer_id = $pdo->lastInsertId();
            }

            /* 2. Lock Branch Sequence */
            $stmtSeq = $pdo->prepare(
                "SELECT last_number 
                 FROM branch_sequences 
                 WHERE branch_id = ? 
                 FOR UPDATE"
            );
            $stmtSeq->execute([$branch_id]);
            $lastNumber = $stmtSeq->fetchColumn();

            if ($lastNumber === false) {
                throw new Exception("Branch sequence not initialized.");
            }

            $nextNumber = ((int)$lastNumber) + 1;

// Update sequence
$stmtUpdateSeq = $pdo->prepare(
    "UPDATE branch_sequences 
     SET last_number = ? 
     WHERE branch_id = ?"
);
$stmtUpdateSeq->execute([$nextNumber, $branch_id]);

// Format numeric portion
if ($branch_id == 2) {
    $numericPart = str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
} else {
    $numericPart = $nextNumber;
}

$bill_number = $branch_id . '-' . $numericPart;


            /* 5. Insert Bill */
            $stmtInsertBill = $pdo->prepare(
    "INSERT INTO bills (
        customer_id,
        bill_number,
        in_date,
        branch_id,
        created_by,
        status,
        ready_sms_sent
    ) VALUES (?, ?, ?, ?, ?, 'Pending', 0)"
);

$stmtInsertBill->execute([
    $customer_id,
    $bill_number,
    $in_date,
    $branch_id,
    $_SESSION['user_id']
]);

$bill_id = $pdo->lastInsertId();

/* =============================
   AUDIT LOG - BILL CREATED
============================= */

logAudit(
    $pdo,
    'BILL CREATED',
    'bills',
    $bill_id,
    $branch_id,
    "Bill #{$bill_number} created"
);

/* 6. Pickup Conversion */
if (!empty($_GET['pickup_id'])) {

    $pickup_id = (int)$_GET['pickup_id'];

    $stmtPickup = $pdo->prepare("
        UPDATE pickup 
        SET status = 'Converted', converted_bill = ?
        WHERE pickup_id = ?
    ");
    $stmtPickup->execute([$bill_number, $pickup_id]);

    logAudit(
        $pdo,
        'PICKUP CONVERTED',
        'pickup',
        $pickup_id,
        $branch_id,
        "Pickup converted to Bill #{$bill_number}"
    );
}

            $pdo->commit();

            header("Location: add_jobs.php?bill=" . urlencode($bill_number));
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $message = "Database Error: " . $e->getMessage();
        }
    }
}
?>

<?php include '../includes/header.php'; ?>

<style>
.page-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 40px;
    margin-bottom: 60px;
}

.bill-box {
    background: #ffffff;
    padding: 35px;
    width: 100%;
    max-width: 520px;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.08);
}

.bill-box h2 {
    margin-bottom: 20px;
    text-align: center;
}

.bill-preview {
    background: #eaf3ff;
    padding: 12px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-weight: bold;
    text-align: center;
}

.bill-box label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
}

.bill-box input {
    width: 100%;
    padding: 12px;
    margin-bottom: 18px;
    border-radius: 8px;
    border: 1px solid #ddd;
    font-size: 14px;
}

.bill-box button {
    width: 100%;
    padding: 12px;
    border-radius: 8px;
    border: none;
    background: #007BFF;
    color: #fff;
    font-size: 15px;
    cursor: pointer;
}

.bill-box button:hover {
    background: #0056b3;
}

.error {
    color: red;
    margin-bottom: 15px;
    text-align: center;
}
</style>

<script>
async function fetchCustomerName() {
    const phone = document.getElementById('customer_contact').value.trim();

    if (/^0\d{9}$/.test(phone)) {
        const response = await fetch('/ajax/fetch_customer.php?phone=' + encodeURIComponent(phone));
        if (response.ok) {
            const data = await response.json();
            if (data.name) {
                document.getElementById('customer_name').value = data.name;
            }
        }
    }
}
</script>
<?php if (count($accessibleBranches) > 1): ?>
<form method="get">
    <label>Select Branch</label>
    <select name="branch" onchange="this.form.submit()">
        <option value="">-- Choose Branch --</option>
        <?php foreach ($accessibleBranches as $b): ?>
            <option value="<?= $b ?>" <?= $b == $branch_id ? 'selected' : '' ?>>
                Branch <?= $b ?>
            </option>
        <?php endforeach; ?>
    </select>
</form>
<?php endif; ?>

<div class="page-wrapper">
    <div class="bill-box">

        <h2>Create New Bill</h2>

        <?php if ($message): ?>
            <div class="error"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <div class="bill-preview">
            Next Bill Number: <?= htmlspecialchars($previewNumber) ?>
        </div>

        <form method="post">

            <label>Customer Contact No</label>
            <input type="text" 
                   name="customer_contact" 
                   id="customer_contact"
                   required 
                   maxlength="10"
                   placeholder="07XXXXXXXX"
                   onblur="fetchCustomerName()"
                   value="<?= htmlspecialchars($_POST['customer_contact'] ?? $prefill_contact) ?>"

            <label>Customer Name</label>
            <input type="text" 
                   name="customer_name" 
                   id="customer_name"
                   required
                   value="<?= htmlspecialchars($_POST['customer_name'] ?? $prefill_name) ?>"

            <label>In Date</label>
            <input type="date" 
                   name="in_date" 
                   required
                   value="<?= htmlspecialchars($_POST['in_date'] ?? date('Y-m-d')) ?>">

            <button type="submit">Save & Add Jobs</button>

        </form>

    </div>
</div>

<?php include '../includes/footer.php'; ?>
