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

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

$employee_id = isset($_GET['employee_id']) ? intval($_GET['employee_id']) : 0;
$success_message = "";
$error_message = "";

// Get employee details
$sql = "SELECT * FROM employees WHERE id = '$employee_id'";
$result = mysqli_query($conn, $sql);
$employee = mysqli_fetch_assoc($result);

if(!$employee) {
    header("Location: employees.php");
    exit();
}

// Get bank accounts
$bank_accounts_sql = "SELECT id, bank_name, account_title, balance FROM bank_accounts ORDER BY bank_name";
$bank_accounts_result = mysqli_query($conn, $bank_accounts_sql);

// Add Paid Entry (Recovery)
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_paid'])) {
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $date_time = date('Y-m-d H:i:s');
    
    if($amount <= 0) {
        $error_message = "Please enter valid amount!";
    } elseif($payment_method == 'bank' && $bank_id == 0) {
        $error_message = "Please select a bank account for bank payment!";
    } elseif($amount > $employee['balance']) {
        $error_message = "Recovery amount cannot exceed employee balance (Rs " . number_format($employee['balance'], 2) . ")";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            // Get current balance
            $current_balance = $employee['balance'];
            $new_balance = $current_balance - $amount;
            
            // Insert into employee_ledger
            $insert_sql = "INSERT INTO employee_ledger (employee_id, entry_type, amount, payment_method, bank_id, description, date_time) 
                           VALUES ('$employee_id', 'Recovery', '$amount', '$payment_method', " . ($bank_id ? "'$bank_id'" : "NULL") . ", '$description', '$date_time')";
            mysqli_query($conn, $insert_sql);
            $ledger_id = mysqli_insert_id($conn);
            
            // Update employee balance
            $update_sql = "UPDATE employees SET balance = '$new_balance' WHERE id = '$employee_id'";
            mysqli_query($conn, $update_sql);
            
            // Handle payment method transactions
            if($payment_method == 'bank' && $bank_id > 0) {
                // Update bank account (deposit)
                $update_bank = "UPDATE bank_accounts SET balance = balance + $amount WHERE id = '$bank_id'";
                mysqli_query($conn, $update_bank);
                
                // Add to bank book
                $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                  VALUES ('$bank_id', 'Deposit', '$amount', 'Employee Recovery - " . mysqli_real_escape_string($conn, $employee['employee_name']) . "', 'EMP-REC-$employee_id', '$date_time')";
                mysqli_query($conn, $bank_book_sql);
            } else {
                // Cash payment - add to cash book as income
                $cash_book_sql = "INSERT INTO cash_book (entry_type, amount, description, reference_no, reference_table, reference_id, date_time, user_name) 
                                  VALUES ('income', '$amount', 'Employee Recovery - " . mysqli_real_escape_string($conn, $employee['employee_name']) . "', 'EMP-REC-$employee_id', 'employee_ledger', '$ledger_id', '$date_time', '" . $_SESSION['username'] . "')";
                mysqli_query($conn, $cash_book_sql);
            }
            
            mysqli_commit($conn);
            header("Location: employee_detail.php?employee_id=$employee_id&msg=paid_added");
            exit();
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}
?>

<?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>Add Paid - <?php echo htmlspecialchars($employee['employee_name']); ?></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>
        * { font-family: 'Poppins', sans-serif; }
        body { background: #f5f5f5; }
        .page-header { background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%); border-radius: 15px; padding: 25px 30px; margin-bottom: 30px; color: #fff; }
        .form-card { background: #fff; border-radius: 15px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.05); max-width: 600px; margin: 0 auto; }
        .card-header-custom { background: #28a745; padding: 15px 20px; color: #fff; }
        .card-header-custom h4 { margin: 0; font-size: 18px; }
        .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; }
        .form-control:focus, .form-select:focus { border-color: #28a745; box-shadow: 0 0 0 3px rgba(40,167,69,0.1); }
        .btn-submit { background: #28a745; color: #fff; border: none; padding: 12px 30px; border-radius: 10px; font-weight: 700; width: 100%; }
        .btn-submit:hover { background: #1e7e34; color: #fff; }
        .btn-back { background: #6c757d; color: #fff; padding: 10px 20px; border-radius: 8px; text-decoration: none; font-weight: 600; }
        .btn-back:hover { background: #5a6268; color: #fff; }
        .balance-card { background: #d4edda; border-radius: 12px; padding: 15px; text-align: center; margin-bottom: 20px; border: 1px solid #c3e6cb; }
        .balance-amount { font-size: 28px; font-weight: 800; color: #155724; }
        .info-text { font-size: 12px; color: #6c757d; margin-top: 5px; }
        .required { color: #dc3545; }
        .bank-info-box { background: #e3f2fd; border-radius: 12px; padding: 12px 15px; margin-bottom: 20px; border-left: 4px solid #1976d2; }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-money-bill-wave"></i> Add Paid Entry</h2>
            <p>Add Recovery payment from <?php echo htmlspecialchars($employee['employee_name']); ?></p>
        </div>
        <div>
            <a href="employee_detail.php?employee_id=<?php echo $employee_id; ?>" class="btn-back">
                <i class="fas fa-arrow-left"></i> Back to Employee
            </a>
        </div>
    </div>
    
    <div class="form-card">
        <div class="card-header-custom">
            <h4><i class="fas fa-undo-alt"></i> Recovery Entry Form</h4>
        </div>
        <div class="card-body-custom">
            <div class="balance-card">
                <div class="balance-amount">Rs <?php echo number_format($employee['balance'], 2); ?></div>
                <div>Current Outstanding Balance</div>
                <small>After adding paid entry, balance will decrease</small>
            </div>
            
            <?php if($error_message): ?>
                <div class="alert alert-danger"><?php echo $error_message; ?></div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="mb-3">
                    <label class="form-label"><i class="fas fa-money-bill-wave"></i> Payment Method <span class="required">*</span></label>
                    <select name="payment_method" id="payment_method" class="form-select" required onchange="toggleBankField()">
                        <option value="cash">Cash</option>
                        <option value="bank">Bank Transfer</option>
                    </select>
                </div>
                
                <div class="mb-3" id="bank_div" style="display: none;">
                    <label class="form-label"><i class="fas fa-university"></i> Select Bank Account <span class="required">*</span></label>
                    <select name="bank_id" id="bank_id" class="form-select">
                        <option value="">-- Select Bank Account --</option>
                        <?php while($bank = mysqli_fetch_assoc($bank_accounts_result)): ?>
                            <option value="<?php echo $bank['id']; ?>" data-bank-balance="<?php echo $bank['balance']; ?>">
                                <?php echo htmlspecialchars($bank['bank_name']); ?> - <?php echo htmlspecialchars($bank['account_title']); ?> 
                                (Balance: Rs <?php echo number_format($bank['balance'], 2); ?>)
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="bank-info-box" id="bankInfoBox" style="display: none;">
                    <div class="info-row">
                        <span><i class="fas fa-university"></i> Bank Balance:</span>
                        <strong id="displayBankBalance">Rs 0.00</strong>
                    </div>
                    <div class="info-row">
                        <span><i class="fas fa-arrow-up"></i> Effect on Bank:</span>
                        <strong id="displayBankEffect" style="color: #28a745;">+ Rs 0.00</strong>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label"><i class="fas fa-rupee-sign"></i> Amount <span class="required">*</span></label>
                    <input type="number" step="0.01" name="amount" id="amount" class="form-control" placeholder="Enter amount" required onkeyup="validateAmount()">
                    <div class="info-text" id="amountHint">Maximum recovery: Rs <?php echo number_format($employee['balance'], 2); ?></div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label"><i class="fas fa-file-alt"></i> Description</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="e.g., Recovery of advance, Salary deduction, etc."></textarea>
                </div>
                
                <button type="submit" name="add_paid" class="btn-submit">
                    <i class="fas fa-save"></i> Add Paid Entry
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    function toggleBankField() {
        const paymentMethod = document.getElementById('payment_method').value;
        const bankDiv = document.getElementById('bank_div');
        const bankInfoBox = document.getElementById('bankInfoBox');
        const isBank = (paymentMethod === 'bank');
        
        bankDiv.style.display = isBank ? 'block' : 'none';
        bankInfoBox.style.display = isBank ? 'block' : 'none';
        
        if(isBank) {
            document.getElementById('bank_id').required = true;
            updateBankInfo();
        } else {
            document.getElementById('bank_id').required = false;
        }
    }
    
    function updateBankInfo() {
        const bankSelect = document.getElementById('bank_id');
        if(!bankSelect || bankSelect.style.display === 'none') return;
        
        const selectedOption = bankSelect.options[bankSelect.selectedIndex];
        const bankBalance = parseFloat(selectedOption.getAttribute('data-bank-balance')) || 0;
        const amount = parseFloat(document.getElementById('amount').value) || 0;
        
        document.getElementById('displayBankBalance').innerHTML = 'Rs ' + bankBalance.toFixed(2);
        document.getElementById('displayBankEffect').innerHTML = '+ Rs ' + amount.toFixed(2);
    }
    
    function validateAmount() {
        const amount = parseFloat(document.getElementById('amount').value) || 0;
        const maxAmount = <?php echo $employee['balance']; ?>;
        const amountHint = document.getElementById('amountHint');
        
        if(amount > maxAmount) {
            amountHint.innerHTML = '<i class="fas fa-exclamation-triangle" style="color: #dc3545;"></i> Amount exceeds balance! Maximum: Rs ' + maxAmount.toFixed(2);
            amountHint.style.color = '#dc3545';
        } else {
            amountHint.innerHTML = 'Maximum recovery: Rs ' + maxAmount.toFixed(2);
            amountHint.style.color = '#6c757d';
        }
        
        updateBankInfo();
    }
    
    document.getElementById('amount')?.addEventListener('input', function() {
        validateAmount();
        updateBankInfo();
    });
    document.getElementById('bank_id')?.addEventListener('change', updateBankInfo);
</script>

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