<?php
session_start();
session_write_close();
ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/Mailer.php';
require __DIR__ . '/includes/auth_init.php';

header('Content-Type: application/json');

if (!$isAdmin) {
    http_response_code(403);
    ob_clean();
    echo json_encode(['error' => 'You do not have permission to send payslips.']);
    exit;
}

$action = $_REQUEST['action'] ?? '';
$cycleId = (int) ($_REQUEST['cycle_id'] ?? 0);

$stmt = $conn->prepare("SELECT * FROM payroll_cycles WHERE id = ?");
$stmt->bind_param('i', $cycleId);
$stmt->execute();
$cycle = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$cycle) {
    http_response_code(404);
    ob_clean();
    echo json_encode(['error' => 'Payroll cycle not found.']);
    exit;
}

// ---------------------------------------------------------------------
// action=queue -- builds the list of payslips to send, split into
// "queue" (has an email, will be attempted) and "skipped" (no email on
// file -- never attempted, never logged as a failure).
// ---------------------------------------------------------------------
if ($action === 'queue') {
    if (!in_array($cycle['status'], ['approved', 'paid'])) {
        ob_clean();
        echo json_encode(['error' => 'This cycle must be fully approved before payslips can be sent.']);
        exit;
    }

    $mode = ($_REQUEST['mode'] ?? '') === 'resend_all' ? 'resend_all' : 'pending';

    $sql = "
        SELECT pr.id, e.name, e.email
        FROM payroll_payslip_runs pr
        JOIN employees e ON e.id = pr.employee_id
        WHERE pr.payroll_cycle_id = $cycleId
    ";
    if ($mode === 'pending') {
        $sql .= " AND pr.id NOT IN (SELECT payroll_run_id FROM payslip_email_log WHERE status = 'sent')";
    }
    $sql .= " ORDER BY e.name ASC";
    $res = $conn->query($sql);

    $queue = [];
    $skipped = [];
    while ($row = $res->fetch_assoc()) {
        if (empty($row['email'])) {
            $skipped[] = ['run_id' => (int) $row['id'], 'name' => $row['name']];
        } else {
            $queue[] = ['run_id' => (int) $row['id'], 'name' => $row['name'], 'email' => $row['email']];
        }
    }

    ob_clean();

    echo json_encode(['queue' => $queue, 'skipped' => $skipped]);
    exit;
}

// ---------------------------------------------------------------------
// action=send_one -- sends exactly one payslip email and logs the result.
// The front end calls this once per employee in the queue, sequentially.
// ---------------------------------------------------------------------
if ($action === 'send_one') {
    $runId = (int) ($_REQUEST['run_id'] ?? 0);

    $stmt = $conn->prepare("
        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.id = ? AND pr.payroll_cycle_id = ?
    ");
    $stmt->bind_param('ii', $runId, $cycleId);
    $stmt->execute();
    $run = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$run) {
        http_response_code(404);
        ob_clean();
        echo json_encode(['error' => 'Payslip not found.']);
        exit;
    }

    $mailer = new Mailer($conn);
    $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();

    if ($result['success']) {
        $conn->query("UPDATE payroll_payslip_runs SET status = 'paid' WHERE id = $runId");
    }

    ob_clean();

    echo json_encode([
        'run_id' => $runId,
        'name' => $run['name'],
        'email' => $run['email'],
        'status' => $status,
        'error' => $error,
    ]);
    exit;
}

// ---------------------------------------------------------------------
// action=finalize -- called once the whole queue has finished, flips
// the cycle to 'paid' if at least one email actually went out.
// ---------------------------------------------------------------------
if ($action === 'finalize') {
    $sentCount = $conn->query("
        SELECT COUNT(*) as c FROM payslip_email_log l
        JOIN payroll_payslip_runs pr ON pr.id = l.payroll_run_id
        WHERE pr.payroll_cycle_id = $cycleId AND l.status = 'sent'
    ")->fetch_assoc()['c'];
    if ($sentCount > 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 AND status != 'paid'");
    }
    ob_clean();
    echo json_encode(['ok' => true]);
    exit;
}

http_response_code(400);
ob_clean();
echo json_encode(['error' => 'Unknown action.']);