<?php
session_start();
include '../../includes/header.php';

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/DeliveryNote.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';

$database = new Database();
$conn = $database->getConnection();

$auth = new Auth($conn);
$branch = new Branch($conn);
$deliveryNote = new DeliveryNote($conn);

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

// ================= BRANCH LOGIC =================
$branchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;

$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);

if ($isSuperAdmin) {

    if (!$branchId) {
       // header('Location: ../admin/requests/request_branch_selection.php?error=' . urlencode('Please select a branch.'));
        exit();
    }

    $branches = $branch->getAllBranches();
    $validBranch = false;

    foreach ($branches->fetchAll(PDO::FETCH_ASSOC) as $b) {
        if ($b['branch_id'] == $branchId) {
            $validBranch = true;
            break;
        }
    }

    if (!$validBranch) {
     //   header('Location: ../admin/requests/request_branch_selection.php?error=' . urlencode('Invalid branch selected.'));
        exit();
    }

    $_SESSION['selected_branch_id'] = $branchId;

} else {

    $branchId = $userBranchId;

    if (!$branchId) {
        header('Location: ../../login.php?error=' . urlencode('No branch assigned.'));
        exit();
    }

    $_SESSION['selected_branch_id'] = $branchId;
}

$isUserAssignedBranch = ($branchId == $userBranchId);

// ================= FETCH DELIVERY NOTES =================
$deliveryNotes = $deliveryNote->getDeliveryNotesByBranch($branchId);



// ================= STATUS FUNCTION =================
function getStatus($created_at, $status) {
    return $status;
}
?>

<style>
.table-container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 20px;
}
.table thead th {
    background-color: #f5f5f5;
    text-align: center;
}
.clickable-row { cursor: pointer; }
.clickable-row:hover { background-color: #f0f0f0; }
.disabled-btn { pointer-events: none; opacity: 0.6; }
@media print { .no-print { display: none; } }
</style>

<div class="container table-container">

<h2 class="mb-4">Delivery Notes - Branch ID: <?php echo htmlspecialchars($branchId); ?></h2>

<?php if (isset($_GET['success'])) { ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_GET['success']); ?></div>
<?php } ?>

<?php if (isset($_GET['error'])) { ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($_GET['error']); ?></div>
<?php } ?>

<table class="table table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Customer</th>
<th>Actions</th>
</tr>
</thead>

<tbody>

<?php if (!empty($deliveryNotes)) { ?>

<?php foreach ($deliveryNotes as $note) {

    $dateTime = new DateTime($note['created_at']);
    $formattedDate = $dateTime->format('Y-m-d');
    $customer_name = htmlspecialchars($note['customer_name']);
?>

<tr class="clickable-row"
onclick="window.location.href='delivery_note_receipt.php?id=<?php echo $note['delivery_note_id']; ?>'">

<td><?php echo $formattedDate; ?></td>

<td> <?php echo $customer_name; ?> </td>

<td onclick="event.stopPropagation();">

<?php if ($isUserAssignedBranch) { ?>

<a href="edit_delivery_note.php?id=<?php echo $note['delivery_note_id']; ?>"
class="btn btn-sm btn-primary">
<i class="fas fa-edit"></i> Edit
</a>

<form action="delete_delivery_note.php" method="POST" style="display:inline;">
<input type="hidden" name="delivery_note_id" value="<?php echo $note['delivery_note_id']; ?>">

<button type="submit"
class="btn btn-sm btn-danger"
onclick="return confirm('Delete this delivery note?');">
<i class="fas fa-trash"></i> Delete
</button>
</form>

<?php } else { ?>

<span class="btn btn-sm btn-primary disabled-btn">Edit</span>
<span class="btn btn-sm btn-danger disabled-btn">Delete</span>

<?php } ?>

<?php if ($status === 'approved') { ?>
<a href="print_delivery_note.php?id=<?php echo $note['delivery_note_id']; ?>"
class="btn btn-sm btn-info">
<i class="fas fa-print"></i> Print
</a>
<?php } ?>

</td>
</tr>

<?php } ?>

<?php } else { ?>

<tr>
<td colspan="3" class="text-center">No Delivery Notes found.</td>
</tr>

<?php } ?>

</tbody>
</table>

<!-- ACTION BUTTONS -->
<div class="mt-4 text-center no-print">

<?php if ($isUserAssignedBranch && !$isSuperAdmin) { ?>

<a href="../sales/create_d_note.php?branch_id=<?php echo $branchId; ?>"
class="btn btn-success">
<i class="fas fa-plus"></i> Create Delivery Note
</a>

<?php } else { ?>

<span class="btn btn-success disabled-btn">Create Delivery Note</span>

<?php } ?>

<?php if ($isSuperAdmin) { ?>

<a href="../sales/request_branch_selection.php"
class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Change Branch
</a>

<?php } else { ?>

<a href="<?php echo getDashboardLink(); ?>"
class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Back
</a>

<?php } ?>

</div>

</div>

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