<?php
include "auth.php";
checkPermission(['admin','manager']);
require_once "db.php";

ini_set('display_errors', 0);
error_reporting(E_ALL);

/* ======================
   CREATE SALARY PAYMENT
====================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {

    $employee_id  = (int)$_POST['employee_id'];
    $salary_month = $_POST['salary_month']; // YYYY-MM
    $paid_amount  = (float)$_POST['paid_amount'];
    $pay_date     = $_POST['pay_date'];
    $note         = trim($_POST['note']);

    /* ======================
       BASE SALARY
    ====================== */
    $empRes = $conn->query("
        SELECT base_salary 
        FROM employees 
        WHERE employee_id = $employee_id
    ");

    if (!$empRes || $empRes->num_rows === 0) {
        die("Invalid employee selected");
    }

    $emp = $empRes->fetch_assoc();
    $base_salary = (float)$emp['base_salary'];

    /* ======================
       ADVANCE PAID (MONTH)
    ====================== */
$advRes = $conn->query("
    SELECT IFNULL(SUM(amount),0) AS total
    FROM advance_pay
    WHERE employee_id = $employee_id
    AND DATE_FORMAT(advance_date,'%Y-%m') = '$salary_month'
");


    if (!$advRes) {
        die("Advance SQL Error: " . $conn->error);
    }

    $advance_deduct = (float)$advRes->fetch_assoc()['total'];

    /* ======================
       SALARY PAID SO FAR
    ====================== */
    $paidRes = $conn->query("
        SELECT IFNULL(SUM(paid_amount),0) AS total
        FROM salary_pay
        WHERE employee_id = $employee_id
        AND salary_month = '$salary_month'
    ");

    if (!$paidRes) {
        die("Salary Paid SQL Error: " . $conn->error);
    }

    $already_paid = (float)$paidRes->fetch_assoc()['total'];

    /* ======================
       PAYABLE CHECK
    ====================== */
    $payable = $base_salary - $advance_deduct - $already_paid;

    if ($payable < 0) {
        $payable = 0;
    }

    if ($paid_amount > $payable) {
        die("Payment exceeds payable salary");
    }

    /* ======================
       INSERT PAYMENT
    ====================== */
    $stmt = $conn->prepare("
        INSERT INTO salary_pay
        (employee_id, salary_month, paid_amount, base_salary, advance_deduct, net_salary, pay_date, note)
        VALUES (?,?,?,?,?,?,?,?)
    ");

    $stmt->bind_param(
        "isddddss",
        $employee_id,
        $salary_month,
        $paid_amount,
        $base_salary,
        $advance_deduct,
        $paid_amount,
        $pay_date,
        $note
    );

    if (!$stmt->execute()) {
        die("Insert Error: " . $stmt->error);
    }

    header("Location: salary-pay.php");
    exit;
}

/* ======================
   DELETE
====================== */
if (isset($_GET['delete'], $_GET['month'])) {
    $employee_id = (int)$_GET['delete'];
    $month = $_GET['month'];

    $conn->query("
        DELETE FROM salary_pay 
        WHERE employee_id = $employee_id 
        AND salary_month = '$month'
    ");

    header("Location: salary-pay.php");
    exit;
}


/* ======================
   EMPLOYEES
====================== */
$employees = $conn->query("
    SELECT employee_id, employee_name, base_salary
    FROM employees
    WHERE status = 'Active'
");

if (!$employees) {
    die("Employee SQL Error: " . $conn->error);
}

/* ======================
   SALARY LIST
====================== */
$salaries = $conn->query("
    SELECT 
        sp.employee_id,
        e.employee_name,
        sp.salary_month,
        MAX(sp.base_salary) AS base_salary,
        MAX(sp.advance_deduct) AS advance_deduct,
        SUM(sp.paid_amount) AS total_paid,
        MAX(sp.pay_date) AS pay_date
    FROM salary_pay sp
    JOIN employees e ON sp.employee_id = e.employee_id
    GROUP BY sp.employee_id, sp.salary_month
    ORDER BY sp.salary_month DESC
");

if (!$salaries) {
    die("Salary SQL Error: " . $conn->error);
}


if (!$salaries) {
    die("Salary SQL Error: " . $conn->error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Salary Pay</title>
<link rel="stylesheet" href="css/style.css">
<style>
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);justify-content:center;align-items:center}
.modal-content{background:#fff;padding:20px;border-radius:10px;width:420px;max-width:95%}
.close{float:right;cursor:pointer;font-weight:bold}
.alert {
    padding: 12px 18px;
    border-radius: 6px;
    margin-bottom: 15px;
    font-weight: 500;
    text-align: center;
}
.alert.success { background:#d1fae5;color:#065f46;border:1px solid #10b981; }
.alert.error { background:#fee2e2;color:#991b1b;border:1px solid #ef4444; }
.form-row{
    margin-bottom: 0;
}
</style>
</head>

<body class="customer-page">

<?php include("global/header.php"); ?>

<main class="main">
<header class="topbar">
    <button class="hamburger" id="hamburger">☰</button>
    <div style="margin-left:8px;font-weight:600;">Dashboard > Salary Pay</div>

    <?php include("global/notify.php"); ?>

    <div class="profile">
        <button class="profile-btn" id="profileBtn">
            <span>Welcome <?php echo $_SESSION['username']; ?></span>
            <img class="avatar" src="https://i.pravatar.cc/80" />
        </button>
        <nav class="dropdown" id="profileDropdown">
            <a href="profile.php">Profile Settings</a>
            <a href="users.php">Users Settings</a>
            <a href="logout.php">Logout</a>
        </nav>
    </div>
</header>

<section class="content">
<div class="container">

<div class="filter-box">
<button class="btn" onclick="openModal()">➕ Pay Salary</button>
</div>

<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>SL</th>
            <th>Employee</th>
            <th>Month</th>
            <th>Base Salary</th>
            <th>Advance</th>
            <th>Paid</th>
            <th>Due</th>
            <th>Date</th>
            <th style="text-align: center;">Action</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $sl = 1;
        while ($row = $salaries->fetch_assoc()):
            $due = $row['base_salary'] - $row['advance_deduct'] - $row['total_paid'];
            if ($due < 0) $due = 0;
        ?>
        <tr>
            <td><?= $sl++ ?></td>
            <td><?= htmlspecialchars($row['employee_name']) ?></td>
            <td><?= htmlspecialchars($row['salary_month']) ?></td>
            <td><?= number_format($row['base_salary'],2) ?></td>
            <td><?= number_format($row['advance_deduct'],2) ?></td>
            <td><?= number_format($row['total_paid'],2) ?></td>
            <td>
                <strong class="<?= $due > 0 ? 'text-danger' : 'text-success' ?>">
                    <?= number_format($due,2) ?>
                </strong>
            </td>
            <td><?= htmlspecialchars($row['pay_date']) ?></td>
            <td class="action-btn">
                <!-- DELETE -->
                <a href="salary-pay.php?delete=<?= $row['employee_id'] ?>&month=<?= $row['salary_month'] ?>"
                   onclick="return confirm('Delete salary record?')"
                   class="btn btn-danger">
                    Delete
                </a>

                <!-- PRINT -->
                <button onclick="printSalary('<?= $row['employee_id'] ?>','<?= $row['salary_month'] ?>')"
                        class="btn btn-primary">
                    Print
                </button>
            </td>
        </tr>
        <?php endwhile; ?>
    </tbody>
</table>


<!-- MODAL -->
<div id="salaryModal" class="modal">
<div class="modal-content">
<h3>Pay Salary</h3>

<form method="post">
<input type="hidden" name="action" value="create">

<div class="form-row">
    <div class="form-group">
        <label>Employee</label>
        <select name="employee_id" id="employee_id" required>
            <option value="">Select Employee</option>
            <?php while ($e = $employees->fetch_assoc()): ?>
                <option value="<?= $e['employee_id'] ?>">
                    <?= htmlspecialchars($e['employee_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="form-group">
        <label>Salary Month</label>
        <input type="month" id="salary_month" name="salary_month" required>
    </div>
</div>
<div class="form-row">
    <div class="form-group">
        <label>Base Salary</label>
        <input type="number" id="base_salary" readonly>
    </div>
    <div class="form-group">
        <label>Advance Remaining</label>
        <input type="number" id="advance_remaining" readonly>
    </div>
</div>
<div class="form-row">
    <div class="form-group">
        <label>Payable Salary</label>
        <input type="number" id="payable_salary" readonly>
    </div>
    <div class="form-group">
        <label>Pay Amount</label>
        <input type="number" step="0.01" name="paid_amount" id="pay_amount" required>
    </div>
</div>
<div class="form-row">
    <div class="form-group">
        <label>Pay Date</label>
        <input type="date" name="pay_date" required>
    </div>
    <div class="form-group">
        <label>Note</label>
        <textarea name="note"></textarea>
    </div>
</div>

<button class="btn">Save</button>
<button type="button" class="btn btn-danger" onclick="closeModal()">Cancel</button>
</form>
</div>
</div>

</div>
</section>

</main>

<script>
const modal = document.getElementById('salaryModal');
function openModal(){ modal.style.display='flex'; }
function closeModal(){ modal.style.display='none'; }
window.onclick=e=>{ if(e.target===modal) closeModal(); }
</script>

<script>
function loadPayableSalary() {
    let emp = document.getElementById('employee_id').value;
    let month = document.getElementById('salary_month').value;

    if (!emp || !month) return;

    fetch(`get_salary_payable.php?employee_id=${emp}&salary_month=${month}`)
        .then(res => res.json())
        .then(data => {
            if (!data.success) return;

            document.getElementById('base_salary').value = data.base_salary.toFixed(2);
            document.getElementById('advance_remaining').value = data.advance_remaining.toFixed(2);
            document.getElementById('payable_salary').value = data.payable_salary.toFixed(2);

            let payInput = document.getElementById('pay_amount');
            payInput.value = data.payable_salary.toFixed(2);
            payInput.max = data.payable_salary;
        });
}

/* Trigger */
document.getElementById('employee_id').addEventListener('change', loadPayableSalary);
document.getElementById('salary_month').addEventListener('change', loadPayableSalary);

/* Prevent over payment */
document.getElementById('pay_amount').addEventListener('input', function(){
    let max = parseFloat(document.getElementById('payable_salary').value || 0);
    if (parseFloat(this.value) > max) this.value = max;
});
</script>
<script>
            // Sidebar accordion & profile dropdown (same behavior as your other pages)
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault();
                    const currentItem = btn.parentElement;
                    const isOpen = currentItem.classList.contains("open");
                    document.querySelectorAll(".has-submenu.open").forEach((li) => {
                        if (li !== currentItem) {
                            li.classList.remove("open");
                            const b = li.querySelector(".menu-link");
                            if (b) b.setAttribute("aria-expanded", "false");
                        }
                    });
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });
            document
                .querySelectorAll(".submenu")
                .forEach((ul) => ul.addEventListener("click", (e) => e.stopPropagation()));
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => sidebar.classList.toggle("active"));
            document.addEventListener("click", (e) => {
                if (
                    !sidebar.contains(e.target) &&
                    !hamburger.contains(e.target) &&
                    sidebar.classList.contains("active")
                ) {
                    sidebar.classList.remove("active");
                }
            });
            const profileBtn = document.getElementById("profileBtn");
            const profileDropdown = document.getElementById("profileDropdown");
            profileBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                const open = profileDropdown.classList.toggle("open");
                profileBtn.setAttribute("aria-expanded", String(open));
            });
            document.addEventListener("click", () => profileDropdown.classList.remove("open"));
        </script>
<script>
function printSalary(employee_id, month) {
    window.open(
        'salary-print.php?employee_id=' + employee_id + '&month=' + month,
        '_blank'
    );
}
</script>


</body>
</html>
