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

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

$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($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: loan_laybuy_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: loan_laybuy_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);


$loansLaybuys = $loanLaybuy->getLoansLaybuysByBranch($branchId);

function getStatus($created_at, $valid_until, $status) {
    $now = new DateTime();
    $validUntil = new DateTime($valid_until);
    if ($now > $validUntil) {
        return 'expired';
    }
    return $status;
}
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <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">Lay-Buys 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>Unique Code</th>
                    <th>Item</th>
                    <th>Customer Name</th>
                    <th>Total</th>
					<th>Paid</th>
					<th>Balance</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($loansLaybuys as $record) {
                    $dateTime = new DateTime($record['created_at']);
                    $formattedDate = $dateTime->format('Y-m-d');
                    $status = getStatus($record['created_at'], $record['valid_until'], $record['status']);
                ?>
                <tr class="clickable-row" onclick="window.location.href='laybuy_and_loans_receipt.php?record_id=<?php echo $record['record_id']; ?>'">
                    <td><?php echo $formattedDate; ?></td>
                    <td><?php echo htmlspecialchars($record['unique_code']); ?></td>
                    <td><?php echo htmlspecialchars($record['item_name']); ?></td><td><?php echo htmlspecialchars($record['customer_name']); ?></td>
                    <td> <?php echo number_format($record['amount'], 2); ?></td>
                    <td> <?php echo number_format($record['total_paid'], 2); ?></td>
					<td> <?php echo number_format(($record['amount']-$record['total_paid']), 2); ?></td>
                   
					<td>
                        <span class="badge badge-<?php echo $status === 'expired' ? 'danger' : ($status === 'approved' ? 'success' : ($status === 'completed' ? 'primary' : 'warning')); ?>">
                            <?php echo ucfirst($status); ?>
                        </span>
                    </td>
                    <td class="action-cell" onclick="event.stopPropagation();">
                        <a href="laybuy_and_loans_receipt.php?record_id=<?php echo $record['record_id']; ?>&print=1" class="btn btn-sm btn-outline-secondary action-btn" title="Print Receipt">
                            <i class="fas fa-print"></i> Print
                        </a>
                        <?php if (($isUserAssignedBranch)&&($record['amount']-$record['total_paid'])) { ?>
                           	<a href="pay_loan_or_laybuy.php?record_id=<?php echo $record['record_id']; ?>" class="btn btn-sm btn-success action-btn">
                                <i class="fas fa-edit"></i> Pay
                            </a>
							<a href="edit_loan_or_laybuy.php?record_id=<?php echo $record['record_id']; ?>" class="btn btn-sm btn-primary action-btn">
                                <i class="fas fa-edit"></i> Edit
                            </a>
                            <form action="delete_loan_or_laybuy.php" method="POST" style="display: inline;">
                                <input type="hidden" name="record_id" value="<?php echo $record['record_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 record?');">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </form>
                        <?php } else { ?>
							<a href="assign_codes.php?record_id=<?php echo $record['record_id'].'&branch_id='.$branchId; ?>" class="btn btn-sm btn-success action-btn">
                                <i class="fas fa-edit"></i> Assign Code(s)
                            </a>
                           <!--	 <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 } ?>
                    </td>
                </tr>
                <?php } ?>
                <?php if (empty($loansLaybuys)) { ?>
                <tr>
                    <td colspan="9" class="text-center">No lay-buys found for this branch.</td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
		
		

        <div class="mt-4 text-center no-print">
            <?php if ($isUserAssignedBranch) { ?>
                <a href="create_loan_or_laybuy.php?branch_id=<?php echo $branchId; ?>" class="btn btn-success">
                    <i class="fas fa-plus"></i> Create New Lay-Buy
                </a>
            <?php } else { ?>
                <span class="btn btn-success disabled-btn">
                    <i class="fas fa-plus"></i> Create New Lay-Buy
                </span>
            <?php } ?>
            <?php if ($isSuperAdmin) { ?>
                <a href="loan_laybuy_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'; ?>

