<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include 'config.php';

if (!isset($conn) || $conn->connect_error) {
    die("DB connection failed");
}

// Role check - only HR/Admin/Superadmin can release
$user_role = $_SESSION['role'] ?? 'employee';
$can_release = in_array($user_role, ['admin', 'superadmin']);

// GET month/year
$month = $_GET['month'] ?? date('n');
$year  = $_GET['year']  ?? date('Y');
$message = '';

// RELEASE PAYSLIPS ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'release_payslips') {
    if (!$can_release) {
        $message = "Unauthorized action.";
    } else {
        $total = $conn->query("SELECT COUNT(*) AS c FROM payroll_belief WHERE month=$month AND year=$year")->fetch_assoc()['c'];
        $approved = $conn->query("SELECT COUNT(*) AS c FROM payroll_belief WHERE month=$month AND year=$year AND status='approved'")->fetch_assoc()['c'];

        if ($total > 0 && $approved == $total) {
            $stmt = $conn->prepare("UPDATE payroll_belief SET status='released' WHERE month=? AND year=?");
            $stmt->bind_param("ii", $month, $year);
            $stmt->execute();
            $message = "<strong>Payslips Released!</strong> Employees can now view/download in their dashboard.";
            $message .= " <a href='generate_payslips.php?month=$month&year=$year' target='_blank' class='alert-link'>Download All PDFs</a>";
        } else {
            $message = "Cannot release: Not all records are MD-approved.";
        }
    }
}

// Fetch distinct months & years for dropdown
$history_res = $conn->query("SELECT DISTINCT month, year FROM payroll_belief ORDER BY year DESC, month DESC");
$months = [];
while ($r = $history_res->fetch_assoc()) $months[] = $r;

// Fetch selected data
$stmt = $conn->prepare("SELECT * FROM payroll_belief WHERE month=? AND year=? ORDER BY employee_id");
$stmt->bind_param("ii", $month, $year);
$stmt->execute();
$result = $stmt->get_result();

$total_payout = $conn->query("SELECT SUM(net_pay) AS total FROM payroll_belief WHERE month=$month AND year=$year")->fetch_assoc()['total'] ?? 0;

// Determine current status
$status_check = $conn->query("SELECT status, COUNT(*) AS cnt FROM payroll_belief WHERE month=$month AND year=$year GROUP BY status ORDER BY cnt DESC LIMIT 1");
$current_status = $status_check && $status_check->num_rows ? $status_check->fetch_assoc()['status'] : 'none';

$all_approved = $conn->query("SELECT COUNT(*) AS c FROM payroll_belief WHERE month=$month AND year=$year AND status='approved'")->fetch_assoc()['c'];
$total_records = $result->num_rows;
$can_show_release = $can_release && $current_status === 'approved' && $all_approved == $total_records;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Old Salary – <?= date('F Y', mktime(0,0,0,$month,1,$year)) ?></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>
        body {font-family:'Segoe UI',sans-serif;background:#f8f9fa;display:flex;}
        .sidebar {width:250px;background:#2c3e50;color:#fff;padding:15px;position:fixed;top:0;bottom:0;}
        .sidebar h2 {text-align:center;margin-bottom:20px;}
        .sidebar a {color:#fff;text-decoration:none;display:block;padding:10px;border-radius:6px;}
        .sidebar a:hover, .sidebar a.active {background:#1abc9c;}
        .content {margin-left:260px;padding:20px;width:100%;}
        .table th {background:#2c3e50;color:white;}
        .release-card {background:#e3f2fd;padding:15px;border-radius:8px;border-left:5px solid #1976d2;}
        .action-area {display:flex;gap:10px;align-items:center;flex-wrap:wrap;}
    </style>
</head>
<body>

<div class="sidebar">
    <h2>Mypeopleconnect</h2>
    <a href="dashboard_admin.php">Organisation Chart</a>
    <a href="manage_users.php">Employee Details</a>
    <a href="attendanceexcel.php">Attendance Excel</a>
    <a href="payroll_excel.php">Payroll Excel</a>
    <a href="payroll_dashboard.php">Payroll</a>
    <a href="hr_approval_salary.php">Advance</a>
    <a href="view_old_salary.php" class="active bg-success text-white">View Old Salary</a>
    <a href="logout.php" class="text-danger">Logout</a>
</div>

<div class="content">
    <div class="dashboard-header bg-white p-3 rounded shadow-sm mb-4">
        <h1>View Old Salary</h1>
        <p class="text-muted">Select month and year to view historical salary records</p>
    </div>

    <!-- Month/Year Selector -->
    <form method="GET" class="row g-2 align-items-center mb-4">
        <div class="col-auto">
            <select name="month" class="form-select form-select-sm">
                <?php for($m=1;$m<=12;$m++): ?>
                    <option value="<?= $m ?>" <?= $m==$month?'selected':'' ?>><?= date('F',mktime(0,0,0,$m)) ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="col-auto">
            <select name="year" class="form-select form-select-sm">
                <?php for($y=date('Y');$y>=2020;$y--): ?>
                    <option value="<?= $y ?>" <?= $y==$year?'selected':'' ?>><?= $y ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="col-auto">
            <button type="submit" class="btn btn-primary btn-sm">View</button>
            <a href="payroll_excel.php" class="btn btn-secondary btn-sm">Back</a>
        </div>
    </form>

    <!-- Status & Release Card -->
    <div class="card p-3 mb-3">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h5><?= date('F Y', mktime(0,0,0,$month,1,$year)) ?> Payroll</h5>
                <p class="mb-0">
                    Total Employees: <strong><?= $result->num_rows ?></strong> |
                    Total Payout: <strong>₹ <?= number_format($total_payout, 2) ?></strong>
                </p>
            </div>
            <div>
                <span class="badge bg-<?= $current_status=='released'?'success':($current_status=='approved'?'info':'secondary') ?> fs-6">
                    <?= ucfirst($current_status) ?>
                </span>
            </div>
        </div>

        <!-- RELEASE PAYSLIPS BUTTON -->
        <?php if ($can_show_release): ?>
        <div class="release-card mt-3">
            <div class="action-area">
                <form method="POST" class="d-inline">
                    <input type="hidden" name="action" value="release_payslips">
                    <input type="hidden" name="month" value="<?= $month ?>">
                    <input type="hidden" name="year" value="<?= $year ?>">
                    <button type="submit" class="btn btn-success btn-sm" 
                            onclick="return confirm('Release payslips for ALL employees for <?= date('F Y', mktime(0,0,0,$month,1,$year)) ?>?\nThey will be able to view/download in their dashboard.')">
                        Release Payslips to Employees
                    </button>
                </form>
                <small class="text-muted ms-2">
                    All records are MD-approved. Ready to release.
                </small>
            </div>
        </div>
        <?php elseif ($current_status === 'released'): ?>
        <div class="alert alert-success mt-3 p-2">
            <strong>Payslips already released!</strong> Employees can view in their dashboard.
            <a href="generate_payslips.php?month=<?= $month ?>&year=<?= $year ?>" target="_blank" class="alert-link ms-2">Re-Download PDFs</a>
        </div>
        <?php elseif ($current_status === 'pending'): ?>
        <div class="alert alert-warning mt-3 p-2">
            Waiting for MD Approval
        </div>
        <?php elseif ($current_status === 'draft'): ?>
        <div class="alert alert-info mt-3 p-2">
            Payroll not sent to MD yet.
        </div>
        <?php endif; ?>

        <!-- Success Message -->
        <?php if ($message): ?>
        <div class="alert <?= strpos($message,'Released')!==false ? 'alert-success' : 'alert-danger' ?> alert-dismissible fade show mt-3">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
    </div>

    <!-- Payroll Table -->
    <?php if ($result->num_rows > 0): ?>
    <div class="table-responsive mt-3">
        <table class="table table-bordered table-striped table-sm">
            <thead>
                <tr>
                    <th>#</th>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Gross</th>
                    <th>Basic</th>
                    <th>HRA</th>
                    <th>Conv</th>
                    <th>PF</th>
                    <th>ESI</th>
                    <th>Tax</th>
                    <th>Net Pay</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php $i=1; $result->data_seek(0); while($r=$result->fetch_assoc()): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($r['employee_id']) ?></td>
                    <td><?= htmlspecialchars($r['employee_name']) ?></td>
                    <td>₹ <?= number_format($r['gross_salary'],2) ?></td>
                    <td>₹ <?= number_format($r['basic'],2) ?></td>
                    <td>₹ <?= number_format($r['hra'],2) ?></td>
                    <td>₹ <?= number_format($r['conv'],2) ?></td>
                    <td>₹ <?= number_format($r['pf'],2) ?></td>
                    <td>₹ <?= number_format($r['esi'],2) ?></td>
                    <td>₹ <?= number_format($r['tax'],2) ?></td>
                    <td class="text-success fw-bold">₹ <?= number_format($r['net_pay'],2) ?></td>
                    <td>
                        <span class="badge bg-<?= $r['status']=='released'?'success':($r['status']=='approved'?'info':'warning') ?>">
                            <?= ucfirst($r['status']) ?>
                        </span>
                    </td>
                </tr>
                <?php endwhile; ?>
                <tr class="table-primary fw-bold">
                    <td colspan="10" class="text-end">TOTAL PAYOUT:</td>
                    <td>₹ <?= number_format($total_payout, 2) ?></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <div class="alert alert-warning mt-4">No records found for this period.</div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>