<?php
/**
 * cron_send_payslips.php
 * -------------------------------------------------------------------
 * Run this from a cron job (e.g. cPanel Cron Jobs) once a day, e.g.:
 *   0 8 * * * php /home/yourcpaneluser/public_html/payroll/cron_send_payslips.php
 *
 * It finds every fully-approved cycle whose end_date (payday) has
 * arrived and hasn't been sent yet, then emails each employee's payslip
 * automatically -- no manual click needed on payday.
 * -------------------------------------------------------------------
 */

date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/Mailer.php';

$today = date('Y-m-d');

$cycles = $conn->query("
    SELECT * FROM payroll_cycles
    WHERE status = 'approved'
    AND end_date <= '$today'
");

$mailer = new Mailer($conn);

while ($cycle = $cycles->fetch_assoc()) {
    $cycleId = $cycle['id'];
    $runs = $conn->query("
        SELECT pr.*, e.name, e.email, pc.name as cycle_name
        FROM payroll_payslip_runs pr
        JOIN employees e ON e.id = pr.employee_id
        JOIN payroll_cycles pc ON pc.id = pr.payroll_cycle_id
        WHERE pr.payroll_cycle_id = $cycleId
        AND e.email IS NOT NULL AND e.email != ''
        AND pr.id NOT IN (SELECT payroll_run_id FROM payslip_email_log WHERE status = 'sent')
    ");

    $sent = 0; $failed = 0; $skipped = 0;
    while ($run = $runs->fetch_assoc()) {
        $subject = "Your Payslip - " . $run['cycle_name'];
        $body = Mailer::payslipEmailTemplate($run);
        $result = $mailer->send($run['email'], $run['name'], $subject, $body);

        $status = $result['success'] ? 'sent' : 'failed';
        $error = $result['error'];
        $logStmt = $conn->prepare("INSERT INTO payslip_email_log (payroll_run_id, recipient_email, status, error_message) VALUES (?, ?, ?, ?)");
        $logStmt->bind_param('isss', $run['id'], $run['email'], $status, $error);
        $logStmt->execute();
        $logStmt->close();

        $result['success'] ? $sent++ : $failed++;
        usleep(400000); // 0.4s pause -- avoids rapid back-to-back SMTP connections some hosts/Mailtrap plans refuse
    }

    $skippedNames = $conn->query("
        SELECT e.name FROM payroll_payslip_runs pr
        JOIN employees e ON e.id = pr.employee_id
        WHERE pr.payroll_cycle_id = $cycleId AND (e.email IS NULL OR e.email = '')
    ");
    while ($s = $skippedNames->fetch_assoc()) { $skipped++; }

    if ($sent > 0) {
        $conn->query("UPDATE payroll_cycles SET status = 'paid' WHERE id = $cycleId");
        $conn->query("UPDATE payroll_payslip_runs SET status = 'paid' WHERE payroll_cycle_id = $cycleId");
        echo "Cycle '{$cycle['name']}': sent $sent, failed $failed, skipped (no email) $skipped\n";
    }
}
