<?php
/**
 * Scheduled report sends - CRUD UI.
 * Cron expressions are stored verbatim. Actual delivery requires a cron
 * job calling bin/run-schedules.php (provided as a stub).
 */
require_once __DIR__ . '/../includes/config.php';
$me = require_login('internal');

$pdo    = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$id     = (int) ($_GET['id'] ?? $_POST['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    if ($action === 'save') {
        $data = [
            'report_id'        => (int) input('report_id'),
            'output_id'        => (int) input('output_id') ?: null,
            'name'             => trim((string) input('name')),
            'cron_expression'  => trim((string) input('cron_expression')),
            'recipients'       => json_encode(array_values(array_filter(array_map('trim', explode(',', (string) input('recipients')))))),
            'output_formats'   => json_encode((array) ($_POST['output_formats'] ?? ['csv'])),
            'subject_template' => trim((string) input('subject_template')) ?: '{report_name} - {period}',
            'body_template'    => trim((string) input('body_template')) ?: 'Attached: {report_name} generated {generated_at}.',
            'status'           => in_array(input('status'), ['active','paused','disabled'], true) ? input('status') : 'active',
        ];
        if ($id) {
            $pdo->prepare('UPDATE scheduled_reports SET report_id=?, output_id=?, name=?, cron_expression=?,
                recipients=?, output_formats=?, subject_template=?, body_template=?, status=?, updated_at=NOW() WHERE id=?')
                ->execute(array_merge(array_values($data), [$id]));
        } else {
            $pdo->prepare('INSERT INTO scheduled_reports
                (report_id, output_id, name, cron_expression, recipients, output_formats,
                 subject_template, body_template, status, created_by, created_at, updated_at)
                VALUES (?,?,?,?,?,?,?,?,?,?,NOW(),NOW())')
                ->execute(array_merge(array_values($data), [$me['id']]));
            $id = (int) $pdo->lastInsertId();
        }
        audit_log($action === 'save' && $id ? 'schedule.save' : 'schedule.create', 'scheduled_report', $id, null, $data);
        flash('success', 'Schedule saved.');
        redirect('/admin/scheduled.php');
    }
    if ($action === 'delete' && $id) {
        $pdo->prepare('DELETE FROM scheduled_reports WHERE id=?')->execute([$id]);
        audit_log('schedule.delete', 'scheduled_report', $id);
        flash('success', 'Schedule removed.');
        redirect('/admin/scheduled.php');
    }
}

$reports = $pdo->query("SELECT id, name, code FROM reports WHERE deleted_at IS NULL AND status='active' ORDER BY name")->fetchAll();

$pageTitle = 'Scheduled reports';
require __DIR__ . '/../includes/header.php';

if ($action === 'new' || $action === 'edit') {
    $row = ['id'=>0,'report_id'=>0,'output_id'=>0,'name'=>'','cron_expression'=>'0 9 * * 1',
            'recipients'=>'[]','output_formats'=>'["csv"]',
            'subject_template'=>'','body_template'=>'','status'=>'active'];
    if ($action === 'edit' && $id) {
        $st = $pdo->prepare('SELECT * FROM scheduled_reports WHERE id=?');
        $st->execute([$id]); $row = $st->fetch() ?: $row;
    }
    $outputs = [];
    if ($row['report_id']) {
        $os = $pdo->prepare('SELECT id, output_name FROM report_outputs WHERE report_id=? ORDER BY display_order');
        $os->execute([$row['report_id']]); $outputs = $os->fetchAll();
    }
?>
<div class="page-header"><div class="container-xl">
    <h2 class="page-title"><?= $action === 'edit' ? 'Edit schedule' : 'New schedule' ?></h2>
</div></div>
<div class="page-body"><div class="container-xl"><div class="card">
<form method="POST" action="?action=save" class="card-body">
    <?= csrf_field() ?>
    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
    <div class="row g-3">
        <div class="col-md-6"><label class="form-label required">Report</label>
            <select name="report_id" class="form-select" required>
                <option value="">-- choose --</option>
                <?php foreach ($reports as $r): ?><option value="<?= $r['id'] ?>" <?= $row['report_id']==$r['id']?'selected':'' ?>><?= e($r['name']) ?></option><?php endforeach; ?>
            </select></div>
        <div class="col-md-6"><label class="form-label">Output (blank = entire dashboard)</label>
            <select name="output_id" class="form-select">
                <option value="">All outputs</option>
                <?php foreach ($outputs as $o): ?><option value="<?= $o['id'] ?>" <?= $row['output_id']==$o['id']?'selected':'' ?>><?= e($o['output_name']) ?></option><?php endforeach; ?>
            </select></div>
        <div class="col-md-6"><label class="form-label required">Schedule name</label><input type="text" name="name" class="form-control" required value="<?= e($row['name']) ?>"></div>
        <div class="col-md-3"><label class="form-label required">Cron expression</label><input type="text" name="cron_expression" class="form-control" required value="<?= e($row['cron_expression']) ?>" placeholder="0 9 * * 1"></div>
        <div class="col-md-3"><label class="form-label">Status</label>
            <select name="status" class="form-select">
                <?php foreach (['active','paused','disabled'] as $s): ?><option value="<?= $s ?>" <?= $row['status']===$s?'selected':'' ?>><?= $s ?></option><?php endforeach; ?>
            </select></div>
        <div class="col-12"><label class="form-label">Recipients (comma-separated emails)</label>
            <input type="text" name="recipients" class="form-control" value="<?= e(implode(', ', json_decode($row['recipients'] ?: '[]', true) ?: [])) ?>"></div>
        <div class="col-12"><label class="form-label">Output formats</label>
            <?php $fmts = json_decode($row['output_formats'] ?: '[]', true) ?: ['csv']; ?>
            <?php foreach (['csv','pdf','xlsx'] as $f): ?>
                <label class="form-check form-check-inline"><input type="checkbox" name="output_formats[]" value="<?= $f ?>" <?= in_array($f, $fmts, true)?'checked':'' ?> class="form-check-input"><span class="form-check-label"><?= $f ?></span></label>
            <?php endforeach; ?>
        </div>
        <div class="col-md-6"><label class="form-label">Email subject template</label>
            <input type="text" name="subject_template" class="form-control" value="<?= e($row['subject_template'] ?: '{report_name} - {period}') ?>"></div>
        <div class="col-md-6"><label class="form-label">Email body template</label>
            <textarea name="body_template" class="form-control" rows="2"><?= e($row['body_template'] ?: 'Attached: {report_name} generated {generated_at}.') ?></textarea></div>
        <div class="col-12 small text-secondary">
            Placeholders: <code>{report_name}</code> <code>{period}</code> <code>{generated_at}</code>.
            Cron quick reference: <code>0 9 * * 1</code> = every Mon 9am, <code>0 8 1 * *</code> = 1st of month 8am, <code>0 6 * * *</code> = daily 6am.
        </div>
    </div>
    <div class="form-footer"><a href="<?= e(url('/admin/scheduled.php')) ?>" class="btn btn-link">Cancel</a><button class="btn btn-primary"><i class="ti ti-check me-1"></i>Save schedule</button></div>
</form>
</div></div></div>
<?php
} else {
    $rows = $pdo->query("SELECT s.*, r.name AS report_name, r.code AS report_code,
        o.output_name FROM scheduled_reports s
        LEFT JOIN reports r ON r.id = s.report_id
        LEFT JOIN report_outputs o ON o.id = s.output_id
        ORDER BY s.status, s.name")->fetchAll();
?>
<div class="page-header"><div class="container-xl">
    <div class="row align-items-center">
        <div class="col"><h2 class="page-title">Scheduled reports</h2><div class="text-secondary">Auto-deliver report outputs by email on a cron schedule.</div></div>
        <div class="col-auto"><a href="?action=new" class="btn btn-primary"><i class="ti ti-plus me-1"></i>New schedule</a></div>
    </div>
</div></div>
<div class="page-body"><div class="container-xl"><div class="card">
    <table class="table table-vcenter card-table">
        <thead><tr><th>Name</th><th>Report</th><th>Output</th><th>Cron</th><th>Recipients</th><th>Status</th><th>Last run</th><th></th></tr></thead>
        <tbody>
        <?php if (!$rows): ?><tr><td colspan="8" class="text-secondary text-center py-4">No schedules yet.</td></tr>
        <?php else: foreach ($rows as $r): ?>
            <tr>
                <td><strong><?= e($r['name']) ?></strong></td>
                <td><?= e($r['report_name']) ?></td>
                <td class="small"><?= e($r['output_name'] ?? 'all outputs') ?></td>
                <td><code><?= e($r['cron_expression']) ?></code></td>
                <td class="small"><?= e(implode(', ', json_decode($r['recipients'] ?: '[]', true) ?: [])) ?></td>
                <td>
                    <?php $cls = ['active'=>'success','paused'=>'warning','disabled'=>'secondary'][$r['status']] ?? 'secondary'; ?>
                    <span class="badge bg-<?= $cls ?>-lt"><?= e($r['status']) ?></span>
                    <?php if ($r['consecutive_failures']): ?><span class="badge bg-danger-lt ms-1"><?= (int)$r['consecutive_failures'] ?> fails</span><?php endif; ?>
                </td>
                <td class="small text-secondary"><?= e($r['last_run_at'] ?? '--') ?></td>
                <td>
                    <a href="?action=edit&id=<?= $r['id'] ?>" class="btn btn-sm"><i class="ti ti-edit"></i></a>
                    <form method="POST" action="?action=delete&id=<?= $r['id'] ?>" style="display:inline" onsubmit="return confirm('Delete schedule?');">
                        <?= csrf_field() ?><button class="btn btn-sm btn-ghost-danger"><i class="ti ti-trash"></i></button>
                    </form>
                </td>
            </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table>
</div>
<div class="alert alert-info mt-3 small">
    <strong>Setup the worker:</strong> add this to Windows Task Scheduler (every 1 min):<br>
    <code>"C:\xampp\php\php.exe" "C:\Users\Admin\Desktop\Software\medmecs\bin\run-schedules.php"</code>
</div>
</div></div>
<?php
}
require __DIR__ . '/../includes/footer.php';
