<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../config/mailer.php';
require_once __DIR__ . '/../emails/templates.php';

$user   = requireRole([1, 2]);  // Admin + Dev only
$db     = getDB();
$action = post('action', '');

switch ($action) {

    // ── GET: settings + rules ────────────────────────────────
    case 'get_settings': {
        $cfg = [];
        $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group='email'");
        foreach ($stmt->fetchAll() as $r) $cfg[$r['setting_key']] = $r['setting_value'];

        $rules = $db->query("SELECT * FROM email_notification_rules ORDER BY id")->fetchAll();
        apiSuccess(['settings' => $cfg, 'rules' => $rules]);
    }

    // ── SAVE: email settings ─────────────────────────────────
    case 'save_settings': {
        $fields = ['email_enabled','email_smtp_host','email_smtp_port','email_smtp_secure',
                   'email_smtp_user','email_smtp_pass','email_from_address','email_from_name',
                   'email_admin_address','email_app_url'];
        $stmt = $db->prepare("INSERT INTO settings (setting_key,setting_value,setting_group,label,input_type)
            VALUES (?,?,'email',?,?) ON DUPLICATE KEY UPDATE setting_value=?");
        foreach ($fields as $f) {
            $val = post($f, '');
            $stmt->execute([$f, $val, $f, 'text', $val]);
        }
        apiSuccess([], 'Email settings saved.');
    }

    // ── SAVE: notification rules ─────────────────────────────
    case 'save_rules': {
        $rules = post('rules', []);
        if (!is_array($rules)) apiError('Invalid rules.', 422);
        $stmt = $db->prepare("
            UPDATE email_notification_rules SET
              is_enabled=?, notify_admin=?, notify_assigned_tech=?,
              notify_client=?, notify_role_ids=?, custom_recipients=?, include_pdf=?
            WHERE event_type=?
        ");
        foreach ($rules as $r) {
            $roleIds = trim($r['notify_role_ids'] ?? '');
            // Derive notify_admin from whether Admin role (1) is ticked
            $roleArr     = array_filter(array_map('trim', explode(',', $roleIds)));
            $notifyAdmin = in_array('1', $roleArr) ? 1 : 0;
            $stmt->execute([
                (int)($r['is_enabled']          ?? 0),
                $notifyAdmin,
                (int)($r['notify_assigned_tech'] ?? 0),
                (int)($r['notify_client']        ?? 0),
                $roleIds,
                trim($r['custom_recipients']     ?? ''),
                (int)($r['include_pdf']          ?? 0),
                $r['event_type'],
            ]);
        }
        apiSuccess([], 'Notification rules saved.');
    }

    // ── TEST: send a test email ──────────────────────────────
    case 'test_send': {
        $toEmail = trim(post('to_email', ''));
        if (!filter_var($toEmail, FILTER_VALIDATE_EMAIL)) apiError('Invalid email address.', 422);

        $cfg = _loadEmailCfg($db);
        if (empty($cfg['email_smtp_host'])) apiError('SMTP not configured. Please save settings first.', 422);

        $mailer = new EWGMailer([
            'host'       => $cfg['email_smtp_host'],
            'port'       => $cfg['email_smtp_port'] ?? 587,
            'secure'     => $cfg['email_smtp_secure'] ?? 'tls',
            'user'       => $cfg['email_smtp_user'],
            'pass'       => $cfg['email_smtp_pass'],
            'from_email' => $cfg['email_from_address'],
            'from_name'  => $cfg['email_from_name'] ?? 'Elegant Work',
        ]);

        $html = emailWrapper('Test Email',
            '<h2 style="color:#111827;margin:0 0 12px">✅ Test Email Successful</h2>
             <p style="color:#6b7280;font-size:14px">Your SMTP configuration is working correctly. Elegant Work email notifications are ready to send.</p>
             <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:16px;margin-top:20px">
               <div style="font-size:13px;color:#166534">Sent via: ' . htmlspecialchars($cfg['email_smtp_host']) . '</div>
             </div>',
            'This is a test email from Elegant Work.'
        );

        $ok = $mailer->send($toEmail, 'Test Recipient', '✅ Elegant Work — Test Email', $html);
        if ($ok) {
            apiSuccess(['debug' => $mailer->debugLog], 'Test email sent successfully!');
        } else {
            apiError('Failed to send: ' . $mailer->lastError, 500, $mailer->debugLog);
        }
    }

    // ── GET: email log ───────────────────────────────────────
    case 'get_log': {
        ['page'=>$page,'limit'=>$limit,'offset'=>$offset] = getPagination();
        $status = post('status', '');

        $where = $status ? "WHERE status=?" : "";
        $params = $status ? [$status] : [];

        $total = $db->prepare("SELECT COUNT(*) FROM email_log $where");
        $total->execute($params);
        $count = (int)$total->fetchColumn();

        $stmt = $db->prepare("SELECT * FROM email_log $where ORDER BY sent_at DESC LIMIT $limit OFFSET $offset");
        $stmt->execute($params);
        $logs = $stmt->fetchAll();

        apiSuccess([
            'logs' => $logs,
            'pagination' => [
                'total' => $count, 'page' => $page,
                'limit' => $limit, 'pages' => ceil($count / $limit),
            ]
        ]);
    }

    // ── GET: queue status ────────────────────────────────────
    case 'get_queue': {
        ['page'=>$page,'limit'=>$limit,'offset'=>$offset] = getPagination();
        $status = post('status', 'pending');
        $params = $status ? [$status] : [];
        $where  = $status ? "WHERE status=?" : "";

        $total = $db->prepare("SELECT COUNT(*) FROM email_queue $where");
        $total->execute($params);
        $count = (int)$total->fetchColumn();

        $stmt = $db->prepare("SELECT * FROM email_queue $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
        $stmt->execute($params);
        $items = $stmt->fetchAll();

        apiSuccess([
            'queue' => $items,
            'pagination' => [
                'total' => $count, 'page' => $page,
                'limit' => $limit, 'pages' => ceil($count / $limit),
            ]
        ]);
    }

    // ── RETRY: reset failed emails to pending ────────────────
    case 'retry_failed': {
        $db->exec("UPDATE email_queue SET status='pending', attempts=0 WHERE status='failed'");
        apiSuccess([], 'Failed emails reset to pending.');
    }

    // ── DELETE: remove specific queued email(s) ───────────────
    case 'delete_queued': {
        $ids = post('ids', []);
        if (!is_array($ids) || empty($ids)) apiError('No IDs provided.', 422);
        $ids = array_filter(array_map('intval', $ids));
        if (empty($ids)) apiError('Invalid IDs.', 422);
        $in = implode(',', $ids);
        $db->exec("DELETE FROM email_queue WHERE id IN ({$in})");
        apiSuccess(['deleted' => count($ids)], count($ids) . ' email(s) removed from queue.');
    }

    // ── DELETE: clear entire queue by status ──────────────────
    case 'clear_queue': {
        $status = post('status', ''); // 'pending', 'failed', or '' for all
        if ($status && !in_array($status, ['pending', 'failed', 'sending'])) apiError('Invalid status.', 422);
        $where = $status ? "WHERE status = ?" : "";
        $params = $status ? [$status] : [];
        $stmt = $db->prepare("DELETE FROM email_queue {$where}");
        $stmt->execute($params);
        apiSuccess(['deleted' => $stmt->rowCount()], 'Queue cleared.');
    }

    // ── CLEAR: remove old sent/failed records ────────────────
    case 'clear_old': {
        $days = max(1, (int)post('days', 30));
        $db->prepare("DELETE FROM email_queue WHERE status IN ('sent','failed') AND created_at < DATE_SUB(NOW(), INTERVAL ? DAY)")->execute([$days]);
        $db->prepare("DELETE FROM email_log WHERE sent_at < DATE_SUB(NOW(), INTERVAL ? DAY)")->execute([$days]);
        apiSuccess([], "Records older than {$days} days cleared.");
    }

    // ── GET: stats summary ───────────────────────────────────
    case 'get_stats': {
        $queueStats = $db->query("SELECT status, COUNT(*) as cnt FROM email_queue GROUP BY status")->fetchAll();
        $logStats   = $db->query("SELECT status, COUNT(*) as cnt FROM email_log WHERE sent_at > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY status")->fetchAll();
        $lastSent   = $db->query("SELECT sent_at FROM email_log WHERE status='sent' ORDER BY sent_at DESC LIMIT 1")->fetchColumn();
        apiSuccess([
            'queue'     => $queueStats,
            'log_30d'   => $logStats,
            'last_sent' => $lastSent,
        ]);
    }

    default:
        apiError('Unknown action.', 400);
}

function _loadEmailCfg(PDO $db): array {
    $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group='email'");
    $cfg = [];
    foreach ($stmt->fetchAll() as $r) $cfg[$r['setting_key']] = $r['setting_value'];
    return $cfg;
}