<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
include '../../includes/header.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Request.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';

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

$auth = new Auth($conn);
$request = new Request($conn);
$branch = new Branch($conn);

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


$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 to this user.'));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
}


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


$requests = $request->getRequestsByBranch($branchId);

function getStatus($created_at, $status) {
    $now = new DateTime();
   // $validUntil = new DateTime($valid_until);
    //if ($now > $validUntil) {
     //   return 'expired';
   // }
    return $status;
}
?>
    <style>
        .table-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }
        .table thead th {
            background-color: #f5f5f5;
            text-align: center;
        }
        .action-btn {
            margin: 0 5px;
        }
        .clickable-row {
            cursor: pointer;
        }
        .clickable-row:hover {
            background-color: #f0f0f0;
        }
        .action-btn {
            pointer-events: auto;
        }
        .disabled-btn {
            pointer-events: none;
            opacity: 0.6;
        }
        @media print {
            .no-print {
                display: none;
            }
        }
    </style>
    <div class="container table-container">
        <h2 class="mb-4">Request List for Branch ID: <?php echo htmlspecialchars($branchId); ?></h2>

        <?php if (isset($_GET['success'])) { ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($_GET['success']); ?></div>
        <?php } elseif (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>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($requests as $request) {
                    $dateTime = new DateTime($request['created_at']);
                    $formattedDate = $dateTime->format('Y-m-d');
                    $status = getStatus($request['created_at'], $request['status']);
                ?>
                <tr class="clickable-row" onclick="window.location.href='request_receipt.php?request_id=<?php echo $request['request_id']; ?>'">
                    <td><?php echo $formattedDate; ?></td>
                    <td>
                        <span class="badge bg-<?php echo $status === 'expired' ? 'danger' : ($status === 'approved' ? 'success' : 'warning'); ?>">
                            <?php echo ucfirst($status); ?>
                        </span>
                    </td>
                    <td class="action-cell" onclick="event.stopPropagation();">
                        <?php if ($isUserAssignedBranch) { ?>
                            <a href="edit_request.php?request_id=<?php echo $request['request_id']; ?>" class="btn btn-sm btn-primary action-btn">
                                <i class="fas fa-edit"></i> Edit
                            </a>
                            <form action="delete_request.php" method="POST" style="display: inline;">
                                <input type="hidden" name="request_id" value="<?php echo $request['request_id']; ?>">
                                <input type="hidden" name="branch_id" value="<?php echo $branchId; ?>">
                                <input type="hidden" name="search_term" value="<?php echo htmlspecialchars($_GET['search_term'] ?? ''); ?>">
                                <input type="hidden" name="search_field" value="<?php echo htmlspecialchars($_GET['search_field'] ?? ''); ?>">
                                <button type="submit" class="btn btn-sm btn-danger action-btn" onclick="return confirm('Are you sure you want to delete this request?');">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </form>
                        <?php } else { ?>
                            <span class="btn btn-sm btn-primary action-btn disabled-btn">
                                <i class="fas fa-edit"></i> Edit
                            </span>
                            <span class="btn btn-sm btn-danger action-btn disabled-btn">
                                <i class="fas fa-trash"></i> Delete
                            </span>
                        <?php } ?>
                        <?php if ($status === 'approved') { ?>
                            
                        <?php } ?>
                    </td>
                </tr>
                <?php } ?>
                <?php if (empty($requests)) { ?>
                <tr>
                    <td colspan="4" class="text-center">No requests found for this branch.</td>
                </tr>
                <?php } ?>
            </tbody>
        </table>

        <div class="mt-4 text-center no-print">
            <?php if ($isUserAssignedBranch && !$isSuperAdmin) { ?>
                <a href="../sales/request.php?branch_id=<?php echo $branchId; ?>" class="btn btn-success">
                    <i class="fas fa-plus"></i> Create New Request
                </a>
            <?php } else { ?>
                <span class="btn btn-success disabled-btn">
                    <i class="fas fa-plus"></i> Create New Request
                </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 to Dashboard
                </a>
            <?php } ?>
        </div>
    </div>

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