<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$selected_employee_id = isset($_GET['employee_id']) ? $_GET['employee_id'] : '';

// Get all employees
$employees_sql = "SELECT * FROM employees ORDER BY employee_name";
$employees_result = mysqli_query($conn, $employees_sql);

// Get employee details if selected
$employee_name = "";
$current_balance = 0;
$employee_designation = "";
$employee_phone = "";

if($selected_employee_id) {
    $emp_sql = "SELECT * FROM employees WHERE id = '$selected_employee_id'";
    $emp_result = mysqli_query($conn, $emp_sql);
    if($emp_data = mysqli_fetch_assoc($emp_result)) {
        $employee_name = $emp_data['employee_name'];
        $current_balance = $emp_data['balance'];
        $employee_designation = $emp_data['designation'];
        $employee_phone = $emp_data['phone'];
    }
}

// Get ledger entries for selected employee
$ledger_entries = [];
$total_salary = 0;
$total_advance = 0;
$total_bonus = 0;
$total_recovery = 0;

if($selected_employee_id) {
    $ledger_sql = "SELECT * FROM employee_ledger WHERE employee_id = '$selected_employee_id' ORDER BY id DESC";
    $ledger_result = mysqli_query($conn, $ledger_sql);
    
    while($entry = mysqli_fetch_assoc($ledger_result)) {
        $ledger_entries[] = $entry;
        
        if($entry['entry_type'] == 'Salary') {
            $total_salary += $entry['amount'];
        } elseif($entry['entry_type'] == 'Advance') {
            $total_advance += $entry['amount'];
        } elseif($entry['entry_type'] == 'Bonus') {
            $total_bonus += $entry['amount'];
        } elseif($entry['entry_type'] == 'Recovery') {
            $total_recovery += $entry['amount'];
        }
    }
}
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Ledger</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        
        * {
            font-family: 'Poppins', sans-serif;
        }
        
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Times New Roman', serif;
        }
        
        body {
            background: #f5f5f5;
        }
        
        .page-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            color: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .page-header h2 {
            margin: 0 0 8px 0;
            font-size: 28px;
            color: #fff;
        }
        
        .page-header p {
            margin: 0;
            opacity: 0.95;
            font-weight: 500;
        }
        
        .form-card, .table-card, .summary-card, .employee-info-card {
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .card-header-custom {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            padding: 15px 20px;
            color: #fff;
        }
        
        .card-header-custom h4 {
            margin: 0;
            font-size: 18px;
        }
        
        .card-header-custom i {
            margin-right: 10px;
        }
        
        .card-body-custom {
            padding: 25px;
        }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 15px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #A04657;
            box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
        }
        
        .btn-back {
            background: rgba(255,255,255,0.2);
            color: #fff;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-back:hover {
            background: rgba(255,255,255,0.3);
            color: #fff;
        }
        
        .btn-add-payable {
            background: #ffc107;
            color: #856404;
            padding: 10px 25px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-add-payable:hover {
            background: #e0a800;
            color: #856404;
            transform: translateY(-2px);
        }
        
        .summary-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            text-align: center;
            border-left: 3px solid #A04657;
        }
        
        .stat-label-sm {
            font-size: 12px;
            color: #666;
            font-weight: 500;
            margin-bottom: 5px;
        }
        
        .stat-value-sm {
            font-size: 20px;
            font-weight: 700;
        }
        
        .balance-card {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
        }
        
        .balance-card .label {
            font-size: 14px;
            opacity: 0.9;
            margin-bottom: 10px;
        }
        
        .balance-card .amount {
            font-size: 32px;
            font-weight: 700;
        }
        
        .employee-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
        }
        
        .employee-info-card .info-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        
        .employee-info-card .info-row:last-child {
            border-bottom: none;
        }
        
        .method-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .method-badge.cash {
            background: #e8f5e9;
            color: #2e7d32;
        }
        
        .method-badge.bank {
            background: #e3f2fd;
            color: #1565c0;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 700;
            color: #444;
            border-bottom: 2px solid #dee2e6;
        }
        
        .table td {
            vertical-align: middle;
            font-weight: 500;
        }
        
        .badge-salary {
            background: #17a2b8;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .badge-advance {
            background: #ffc107;
            color: #856404;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .badge-bonus {
            background: #28a745;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .badge-recovery {
            background: #dc3545;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .amount-positive {
            color: #28a745;
            font-weight: 700;
        }
        
        .amount-negative {
            color: #dc3545;
            font-weight: 700;
        }
        
        .select-employee-card {
            text-align: center;
            padding: 50px;
        }
        
        .select-employee-card i {
            font-size: 64px;
            color: #ccc;
            margin-bottom: 20px;
        }
        
        @media (max-width: 768px) {
            .page-header {
                padding: 20px;
                flex-direction: column;
                text-align: center;
            }
            
            .page-header h2 {
                font-size: 22px;
            }
            
            .balance-card .amount {
                font-size: 24px;
            }
            
            .summary-stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-book"></i> Employee Ledger</h2>
            <p>View employee salary, advances, bonuses and recoveries</p>
        </div>
        <div style="display: flex; gap: 10px;">
            <?php if($selected_employee_id): ?>
                <a href="add_employee_payable.php?employee_id=<?php echo $selected_employee_id; ?>" class="btn-add-payable">
                    <i class="fas fa-plus-circle"></i> Add Payable Entry
                </a>
            <?php endif; ?>
            <a href="employees.php" class="btn-back">
                <i class="fas fa-arrow-left"></i> Back to Employees
            </a>
        </div>
    </div>
    
    <div class="row">
        <div class="col-lg-4">
            <div class="form-card">
                <div class="card-header-custom">
                    <h4><i class="fas fa-user"></i> Select Employee</h4>
                </div>
                <div class="card-body-custom">
                    <select id="employee_id" class="form-select" style="font-size: 16px;">
                        <option value="">-- Select Employee --</option>
                        <?php 
                        mysqli_data_seek($employees_result, 0);
                        while($emp = mysqli_fetch_assoc($employees_result)): 
                            $selected = ($selected_employee_id == $emp['id']) ? 'selected' : '';
                        ?>
                            <option value="<?php echo $emp['id']; ?>" <?php echo $selected; ?>>
                                <?php echo htmlspecialchars($emp['employee_name']); ?> - <?php echo htmlspecialchars($emp['designation']); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                    
                    <?php if($selected_employee_id): ?>
                        <div class="mt-4">
                            <div class="employee-info-card">
                                <div class="card-body-custom">
                                    <h5 class="mb-3"><i class="fas fa-user-circle"></i> Employee Details</h5>
                                    <div class="info-row">
                                        <span><i class="fas fa-user"></i> Name:</span>
                                        <strong><?php echo htmlspecialchars($employee_name); ?></strong>
                                    </div>
                                    <div class="info-row">
                                        <span><i class="fas fa-briefcase"></i> Designation:</span>
                                        <strong><?php echo htmlspecialchars($employee_designation); ?></strong>
                                    </div>
                                    <div class="info-row">
                                        <span><i class="fas fa-phone"></i> Phone:</span>
                                        <strong><?php echo htmlspecialchars($employee_phone ?: '—'); ?></strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-lg-8">
            <?php if($selected_employee_id): ?>
                <!-- Summary Section -->
                <div class="summary-card">
                    <div class="card-header-custom">
                        <h4><i class="fas fa-chart-pie"></i> Ledger Summary: <?php echo htmlspecialchars($employee_name); ?></h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="summary-stats">
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-money-bill-wave"></i> Total Salary</div>
                                <div class="stat-value-sm amount-positive">Rs <?php echo number_format($total_salary, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-hand-holding-usd"></i> Total Advance</div>
                                <div class="stat-value-sm amount-positive">Rs <?php echo number_format($total_advance, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-gift"></i> Total Bonus</div>
                                <div class="stat-value-sm amount-positive">Rs <?php echo number_format($total_bonus, 2); ?></div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label-sm"><i class="fas fa-undo-alt"></i> Total Recovery</div>
                                <div class="stat-value-sm amount-negative">Rs <?php echo number_format($total_recovery, 2); ?></div>
                            </div>
                        </div>
                        
                        <div class="balance-card">
                            <div class="label">Current Outstanding Balance</div>
                            <div class="amount">Rs <?php echo number_format($current_balance, 2); ?></div>
                            <small class="mt-2 d-block">
                                <i class="fas fa-info-circle"></i> 
                                Balance = (Salary + Advance + Bonus) - Recovery
                            </small>
                        </div>
                    </div>
                </div>
                
                <!-- Transaction History -->
                <div class="table-card">
                    <div class="card-header-custom">
                        <h4><i class="fas fa-history"></i> Transaction History</h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Entry Type</th>
                                        <th>Amount</th>
                                        <th>Payment Method</th>
                                        <th>Description</th>
                                        <th>Date & Time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(count($ledger_entries) > 0): ?>
                                        <?php foreach($ledger_entries as $index => $entry): ?>
                                            <tr>
                                                <td><?php echo $index + 1; ?></td>
                                                <td>
                                                    <?php if($entry['entry_type'] == 'Salary'): ?>
                                                        <span class="badge-salary"><i class="fas fa-money-bill-wave"></i> Salary</span>
                                                    <?php elseif($entry['entry_type'] == 'Advance'): ?>
                                                        <span class="badge-advance"><i class="fas fa-hand-holding-usd"></i> Advance</span>
                                                    <?php elseif($entry['entry_type'] == 'Bonus'): ?>
                                                        <span class="badge-bonus"><i class="fas fa-gift"></i> Bonus</span>
                                                    <?php else: ?>
                                                        <span class="badge-recovery"><i class="fas fa-undo-alt"></i> Recovery</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="<?php echo ($entry['entry_type'] != 'Recovery') ? 'amount-positive' : 'amount-negative'; ?>">
                                                    <?php echo ($entry['entry_type'] != 'Recovery') ? '+' : '-'; ?> Rs <?php echo number_format($entry['amount'], 2); ?>
                                                </td>
                                                <td>
                                                    <span class="method-badge <?php echo $entry['payment_method'] == 'bank' ? 'bank' : 'cash'; ?>">
                                                        <i class="fas <?php echo $entry['payment_method'] == 'bank' ? 'fa-university' : 'fa-money-bill-wave'; ?>"></i>
                                                        <?php echo ucfirst($entry['payment_method'] ?: 'cash'); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars($entry['description'] ?: '—'); ?></td>
                                                <td>
                                                    <i class="fas fa-calendar-alt"></i> <?php echo date('d-m-Y', strtotime($entry['date_time'])); ?>
                                                    <br><small><?php echo date('h:i A', strtotime($entry['date_time'])); ?></small>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center py-5">
                                                <i class="fas fa-book" style="font-size: 48px; color: #ccc;"></i>
                                                <p class="mt-3 mb-0">No ledger entries found</p>
                                                <small>Click "Add Payable Entry" to add transaction</small>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="form-card select-employee-card">
                    <div class="card-body-custom text-center py-5">
                        <i class="fas fa-user-tie"></i>
                        <h4 class="mt-3">Select an Employee</h4>
                        <p class="text-muted">Please select an employee from the left panel to view their ledger</p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    // Navigate when employee is selected
    document.getElementById('employee_id').addEventListener('change', function() {
        if(this.value) {
            window.location.href = 'employee_ledger.php?employee_id=' + this.value;
        } else {
            window.location.href = 'employee_ledger.php';
        }
    });
</script>

<?php include('../includes/ft.php'); ?>
</body>
</html>