<?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 Payable Entry
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_payable'])) {
    $entry_type = mysqli_real_escape_string($conn, $_POST['entry_type']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $deduction = mysqli_real_escape_string($conn, $_POST['deduction']);
    $final_amount = mysqli_real_escape_string($conn, $_POST['final_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(empty($entry_type) || $final_amount <= 0) {
        $error_message = "Please select entry type and enter valid amount!";
    } elseif($payment_method == 'bank' && $bank_id == 0) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            // Check bank balance if bank payment
            if($payment_method == 'bank' && $bank_id > 0) {
                $bank_check_sql = "SELECT balance FROM bank_accounts WHERE id = '$bank_id'";
                $bank_check_result = mysqli_query($conn, $bank_check_sql);
                $bank_data = mysqli_fetch_assoc($bank_check_result);
                if($bank_data['balance'] < $final_amount) {
                    throw new Exception("Insufficient bank balance! Available: Rs " . number_format($bank_data['balance'], 2));
                }
            }
            
            // Get current balance
            $current_balance = $employee['balance'];
            $new_balance = $current_balance + $final_amount;
            
            // Prepare description with deduction info
            $full_description = $description;
            if($deduction > 0) {
                $full_description .= " (Deduction: Rs " . number_format($deduction, 2) . ", Net Payable: Rs " . number_format($final_amount, 2) . ")";
            }
            
            // 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', '$entry_type', '$final_amount', '$payment_method', " . ($bank_id ? "'$bank_id'" : "NULL") . ", '$full_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 (withdraw)
                $update_bank = "UPDATE bank_accounts SET balance = balance - $final_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', 'Withdrawal', '$final_amount', 'Employee $entry_type - " . mysqli_real_escape_string($conn, $employee['employee_name']) . "', 'EMP-$employee_id', '$date_time')";
                mysqli_query($conn, $bank_book_sql);
            } else {
                // Cash payment - add to cash book as expense
                $cash_book_sql = "INSERT INTO cash_book (entry_type, amount, description, reference_no, reference_table, reference_id, date_time, user_name) 
                                  VALUES ('expense', '$final_amount', 'Employee $entry_type - " . mysqli_real_escape_string($conn, $employee['employee_name']) . "', 'EMP-$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=payable_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 Payable - <?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, #ffc107 0%, #e0a800 100%); border-radius: 15px; padding: 25px 30px; margin-bottom: 30px; color: #856404; display: flex; justify-content: space-between; align-items: center; }
        .form-card { background: #fff; border-radius: 15px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.05); max-width: 650px; margin: 0 auto; }
        .card-header-custom { background: #ffc107; padding: 15px 20px; color: #856404; }
        .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: #ffc107; box-shadow: 0 0 0 3px rgba(255,193,7,0.1); }
        .btn-submit { background: #ffc107; color: #856404; border: none; padding: 12px 30px; border-radius: 10px; font-weight: 700; width: 100%; }
        .btn-submit:hover { background: #e0a800; color: #856404; }
        .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: #fff3cd; border-radius: 12px; padding: 15px; text-align: center; margin-bottom: 20px; border: 1px solid #ffecb5; }
        .balance-amount { font-size: 28px; font-weight: 800; color: #856404; }
        .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; }
        .salary-amount-box { background: #d4edda; border-radius: 12px; padding: 12px 15px; margin-bottom: 20px; border-left: 4px solid #28a745; cursor: pointer; transition: all 0.3s; }
        .salary-amount-box:hover { background: #c3e6cb; }
        .salary-label { font-weight: 600; color: #155724; margin-bottom: 5px; display: flex; align-items: center; gap: 10px; }
        .salary-value { font-size: 24px; font-weight: 800; color: #155724; }
        .deduction-box { background: #fff3cd; border-radius: 12px; padding: 15px; margin-bottom: 20px; border-left: 4px solid #ffc107; }
        .grand-total-box { background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%); border-radius: 12px; padding: 15px; text-align: center; margin-bottom: 20px; }
        .grand-total-label { font-size: 14px; color: #856404; margin-bottom: 5px; }
        .grand-total-value { font-size: 32px; font-weight: 800; color: #856404; }
        .currency-symbol { font-size: 20px; }
        .auto-fetch-btn { background: #28a745; color: white; border: none; border-radius: 20px; padding: 4px 12px; font-size: 12px; font-weight: 600; }
        .auto-fetch-btn:hover { background: #218838; color: white; }
        .info-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-plus-circle"></i> Add Payable Entry</h2>
            <p>Add Salary, Advance, or Bonus payment for <?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-money-bill-wave"></i> Payable 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 payable, balance will increase</small>
            </div>
            
            <?php if($error_message): ?>
                <div class="alert alert-danger"><?php echo $error_message; ?></div>
            <?php endif; ?>
            
            <form method="POST" action="" id="payableForm">
                <div class="mb-3">
                    <label class="form-label"><i class="fas fa-tag"></i> Entry Type <span class="required">*</span></label>
                    <select name="entry_type" id="entry_type" class="form-select" required onchange="updateDescriptionHint(); handleSalaryAutoFetch()">
                        <option value="">-- Select Entry Type --</option>
                        <option value="Salary">💰 Salary (Monthly Payment)</option>
                        <option value="Advance">🏦 Advance (Cash Given)</option>
                        <option value="Bonus">🎁 Bonus (Extra Payment)</option>
                        <option value="Recovery">📉 Recovery (Deduction from Salary)</option>
                    </select>
                    <div class="info-text" id="typeHint"></div>
                </div>
                
                <!-- Salary Auto-Fetch Box -->
                <div id="salaryBox" style="display: none;">
                    <div class="salary-amount-box" onclick="fetchBasicSalary()">
                        <div class="salary-label">
                            <i class="fas fa-money-bill-wave"></i> Basic Salary Amount
                            <span class="auto-fetch-btn"><i class="fas fa-sync-alt"></i> Click to Auto-Fetch</span>
                        </div>
                        <div class="salary-value" id="displayBasicSalary">Rs 0.00</div>
                        <small><i class="fas fa-info-circle"></i> Click the box above to automatically set the basic salary amount</small>
                    </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="calculateGrandTotal()">
                </div>
                
                <!-- Deduction Field -->
                <div id="deductionBox" style="display: none;">
                    <div class="deduction-box">
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-minus-circle"></i> Deduction Amount</label>
                            <input type="number" step="0.01" name="deduction" id="deduction" class="form-control" placeholder="Enter deduction amount" value="0" onkeyup="calculateGrandTotal()">
                            <div class="info-text"><i class="fas fa-info-circle"></i> Enter any deduction (e.g., fine, loan recovery, etc.)</div>
                        </div>
                    </div>
                </div>
                
                <!-- Grand Total Box -->
                <div id="grandTotalBox" style="display: none;">
                    <div class="grand-total-box">
                        <div class="grand-total-label">
                            <i class="fas fa-calculator"></i> FINAL PAYABLE AMOUNT (After Deduction)
                        </div>
                        <div class="grand-total-value">
                            <span class="currency-symbol">Rs</span> <span id="grandTotalDisplay">0.00</span>
                        </div>
                        <input type="hidden" name="final_amount" id="final_amount" value="0">
                        <small><i class="fas fa-info-circle"></i> This is the amount that will be paid to the employee</small>
                    </div>
                </div>
                
                <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 
                        mysqli_data_seek($bank_accounts_result, 0);
                        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-down"></i> Effect on Bank:</span>
                        <strong id="displayBankEffect" style="color: #dc3545;">- Rs 0.00</strong>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label"><i class="fas fa-file-alt"></i> Description</label>
                    <textarea name="description" id="description" class="form-control" rows="3" placeholder="Enter description (e.g., March 2026 Salary, Festival Bonus, etc.)"></textarea>
                </div>
                
                <button type="submit" name="add_payable" class="btn-submit">
                    <i class="fas fa-save"></i> Add Payable Entry
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    // Store basic salary value
    let basicSalary = <?php echo $employee['basic_salary']; ?>;
    
    function handleSalaryAutoFetch() {
        const entryType = document.getElementById('entry_type').value;
        const salaryBox = document.getElementById('salaryBox');
        const deductionBox = document.getElementById('deductionBox');
        const grandTotalBox = document.getElementById('grandTotalBox');
        const amountField = document.getElementById('amount');
        
        if(entryType === 'Salary') {
            salaryBox.style.display = 'block';
            deductionBox.style.display = 'block';
            grandTotalBox.style.display = 'block';
            
            // Auto-fetch basic salary
            if(basicSalary > 0) {
                document.getElementById('displayBasicSalary').innerHTML = 'Rs ' + basicSalary.toFixed(2);
                amountField.value = basicSalary;
                amountField.readOnly = true;
                amountField.style.backgroundColor = '#e9ecef';
                calculateGrandTotal();
            } else {
                document.getElementById('displayBasicSalary').innerHTML = 'Rs 0.00 <span style="color:#dc3545; font-size:12px;">(No basic salary set)</span>';
                amountField.value = '';
                amountField.readOnly = false;
                amountField.style.backgroundColor = '#fff';
            }
        } else {
            salaryBox.style.display = 'none';
            deductionBox.style.display = 'none';
            grandTotalBox.style.display = 'none';
            const amountField = document.getElementById('amount');
            amountField.readOnly = false;
            amountField.style.backgroundColor = '#fff';
        }
        
        updateDescriptionHint();
    }
    
    function fetchBasicSalary() {
        const entryType = document.getElementById('entry_type').value;
        if(entryType === 'Salary' && basicSalary > 0) {
            document.getElementById('amount').value = basicSalary;
            calculateGrandTotal();
            // Show success feedback
            const salaryBox = document.querySelector('.salary-amount-box');
            salaryBox.style.transform = 'scale(1.02)';
            setTimeout(() => { salaryBox.style.transform = 'scale(1)'; }, 300);
        } else if(entryType === 'Salary' && basicSalary <= 0) {
            alert('No basic salary set for this employee. Please set basic salary first in employee edit form.');
        }
    }
    
    function calculateGrandTotal() {
        const amount = parseFloat(document.getElementById('amount').value) || 0;
        const deduction = parseFloat(document.getElementById('deduction').value) || 0;
        const grandTotal = amount - deduction;
        const finalAmount = grandTotal > 0 ? grandTotal : 0;
        
        document.getElementById('grandTotalDisplay').innerHTML = finalAmount.toFixed(2);
        document.getElementById('final_amount').value = finalAmount.toFixed(2);
        
        // Change color if deduction is applied
        const grandTotalElement = document.getElementById('grandTotalDisplay');
        if(deduction > 0) {
            grandTotalElement.style.color = '#dc3545';
        } else {
            grandTotalElement.style.color = '#856404';
        }
        
        updateBankInfo();
    }
    
    function updateDescriptionHint() {
        const entryType = document.getElementById('entry_type').value;
        const hintDiv = document.getElementById('typeHint');
        const descField = document.getElementById('description');
        
        if(entryType == 'Salary') {
            hintDiv.innerHTML = '<i class="fas fa-info-circle"></i> Monthly salary payment. Deductions can be applied for fines, loans, etc.';
            if(!descField.value) descField.placeholder = 'e.g., March 2026 Salary';
        } else if(entryType == 'Advance') {
            hintDiv.innerHTML = '<i class="fas fa-info-circle"></i> Advance payment given to employee (will be recovered later)';
            if(!descField.value) descField.placeholder = 'e.g., Advance for emergency';
        } else if(entryType == 'Bonus') {
            hintDiv.innerHTML = '<i class="fas fa-info-circle"></i> Bonus payment (Eid bonus, Performance bonus, etc.)';
            if(!descField.value) descField.placeholder = 'e.g., Eid ul Fitr Bonus 2026';
        } else if(entryType == 'Recovery') {
            hintDiv.innerHTML = '<i class="fas fa-info-circle"></i> Recovery/Deduction from employee (fine, loan recovery, etc.)';
            if(!descField.value) descField.placeholder = 'e.g., Loan Recovery - Rs 5000';
        } else {
            hintDiv.innerHTML = '';
        }
        
        // Reset amount field when changing entry type
        const amountField = document.getElementById('amount');
        if(entryType !== 'Salary') {
            amountField.value = '';
            amountField.readOnly = false;
            amountField.style.backgroundColor = '#fff';
        }
        
        calculateGrandTotal();
    }
    
    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 finalAmount = parseFloat(document.getElementById('final_amount').value) || 0;
        
        document.getElementById('displayBankBalance').innerHTML = 'Rs ' + bankBalance.toFixed(2);
        document.getElementById('displayBankEffect').innerHTML = '- Rs ' + finalAmount.toFixed(2);
        
        if(finalAmount > bankBalance) {
            document.getElementById('displayBankEffect').innerHTML += ' (Insufficient Balance!)';
            document.getElementById('displayBankEffect').style.color = '#dc3545';
        } else {
            document.getElementById('displayBankEffect').style.color = '#dc3545';
        }
    }
    
    // Add validation before form submit
    document.getElementById('payableForm').addEventListener('submit', function(e) {
        const entryType = document.getElementById('entry_type').value;
        const finalAmount = parseFloat(document.getElementById('final_amount').value);
        
        if(entryType === 'Salary' && finalAmount <= 0) {
            e.preventDefault();
            alert('Please enter a valid final amount (Amount - Deduction should be greater than 0)');
            return false;
        }
    });
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        // Add event listeners
        document.getElementById('amount')?.addEventListener('input', calculateGrandTotal);
        document.getElementById('deduction')?.addEventListener('input', calculateGrandTotal);
        document.getElementById('bank_id')?.addEventListener('change', updateBankInfo);
    });
</script>

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