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

$user = requireRole([1, 2, 4, 5]);
$db = getDB();

$title = trim(post('title', ''));
if (!$title)
    apiError('Job card title required.', 422);

// Generate job number — use MAX of existing sequence to avoid collisions on delete/retry
$year = date('Y');
$month = date('m');
$prefix = sprintf('JC-%s%s-', $year, $month);
$stmt = $db->prepare("SELECT job_number FROM job_cards WHERE 1 ORDER BY id DESC LIMIT 1");
$stmt->execute();
$max = $stmt->fetchAll();
$max = explode('-', $max[0]['job_number'])[2];
$jobNo = $prefix . sprintf('%04d', $max + 1);

$vehicleId = post('vehicle_id') ? (int) post('vehicle_id') : null;
$odoStart = post('odo_start') !== '' && post('odo_start') ? (int) post('odo_start') : null;
$odoEnd = post('odo_end') !== '' && post('odo_end') ? (int) post('odo_end') : null;
$isInternal = post('is_internal') ? 1 : 0;

try {
    $db->prepare("
    INSERT INTO job_cards (
        job_number, client_id, project_id, title, description,
        job_type, status, priority, site_name, site_address,
        scheduled_date, scheduled_time, assigned_to,
        vehicle_id, odo_start, odo_end, is_internal,
        created_by
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
")->execute([
                $jobNo,
                post('client_id') ?: null,
                post('project_id') ?: null,
                $title,
                post('description'),
                post('job_type', 'installation'),
                post('status', 'draft'),
                post('priority', 'normal'),
                post('site_name'),
                post('site_address'),
                post('scheduled_date') ?: null,
                post('scheduled_time') ?: null,
                post('assigned_to') ?: null,
                $vehicleId,
                $odoStart,
                $odoEnd,
                $isInternal,
                $user['id'],
            ]);

    $jobId = (int) $db->lastInsertId();

    // ── Email notification: job_created ───────────────────
    try {
        require_once __DIR__ . '/../config/mailer.php';
        require_once __DIR__ . '/../emails/templates.php';
        $rule = getNotifRule($db, 'job_created');
        if ($rule && $rule['is_enabled']) {
            // Build job data for template
            $jcData = [
                'title' => post('title'),
                'job_number' => $jobNo,
                'client_name' => null,
                'site_name' => post('site_name'),
                'site_address' => post('site_address'),
                'scheduled_date' => post('scheduled_date') ?: null,
                'scheduled_time' => post('scheduled_time') ?: null,
                'description' => post('description'),
                'priority' => post('priority', 'normal'),
                'tech_name' => null,
            ];
            // Get client name + primary contact email
            if (post('client_id')) {
                $cs = $db->prepare("SELECT c.company_name, cc.email AS contact_email, cc.full_name AS contact_name
                    FROM clients c
                    LEFT JOIN client_contacts cc ON cc.client_id = c.id AND cc.is_primary = 1
                    WHERE c.id = ? LIMIT 1");
                $cs->execute([post('client_id')]);
                $cr = $cs->fetch();
                $jcData['client_name'] = $cr['company_name'] ?? null;
                $jcData['client_email'] = $cr['contact_email'] ?? null;
                $jcData['client_contact_name'] = $cr['contact_name'] ?? $cr['company_name'] ?? null;
            }
            // Get tech name
            if (post('assigned_to')) {
                $ts = $db->prepare("SELECT full_name FROM users WHERE id=? LIMIT 1");
                $ts->execute([post('assigned_to')]);
                $jcData['tech_name'] = $ts->fetchColumn() ?: 'Unknown';
            }
            $cfg = getMailerConfig($db);
            $appUrl = $cfg['email_app_url'] ?? '';

            // Company name for client emails
            $companyStmt = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_name' LIMIT 1");
            $companyName = $companyStmt ? ($companyStmt->fetchColumn() ?: 'Elegant Work') : 'Elegant Work';

            $adminEmail = getAdminEmail($db);

            // Admin — internal job created
            if ($rule['notify_admin'] && $adminEmail) {
                $html = tplJobCreated($jcData, 'Admin', $appUrl);
                queueEmail($db, 'job_created', $adminEmail, 'Admin', "📋 New Job Card: {$jobNo}", $html, 'job_card', $jobId);
            }
            // Assigned tech
            if ($rule['notify_assigned_tech'] && post('assigned_to')) {
                $tu = $db->prepare("SELECT email, full_name AS name FROM users WHERE id=? LIMIT 1");
                $tu->execute([post('assigned_to')]);
                $tu = $tu->fetch();
                if ($tu && $tu['email']) {
                    $html = tplJobAssigned($jcData, $tu['name'], $appUrl);
                    queueEmail(
                        $db,
                        'job_assigned',
                        $tu['email'],
                        $tu['name'],
                        "🔧 Job Assigned to You: {$jobNo}",
                        $html,
                        'job_card',
                        $jobId
                    );
                }
                $jcData['tech_name'] = $tu['name'] ?? null;
            }
            // Client — always "planned" on creation regardless of tech assignment
            if ($rule['notify_client'] && !empty($jcData['client_email']) && !post('is_internal')) {
                $clientName = $jcData['client_contact_name'] ?? $jcData['client_name'] ?? 'Valued Client';
                $html = tplClientJobPlanned($jcData, $clientName, $companyName);
                queueEmail(
                    $db,
                    'job_created',
                    $jcData['client_email'],
                    $clientName,
                    "We've Scheduled a Job at Your Site — {$jcData['title']}",
                    $html,
                    'job_card',
                    $jobId
                );
            }
        }
    } catch (Exception $emailErr) {
        error_log('[EWG Email] create trigger failed: ' . $emailErr->getMessage());
    }

    apiSuccess(['id' => $jobId, 'job_number' => $jobNo], 'Job card created.', 201);
} catch (Exception $e) {
    apiError('Failed to create job card: ' . $e->getMessage(), 500);
}