<?php
// ─── POST /api/leads/create.php ──────────────────────────────────────────
// Creates a LEAD or a direct JOBCARD in work_requests (and jobcards if JOBCARD).
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

$user = Auth::require();
$db   = DB::get();

$type             = strtoupper(trim($_POST['type'] ?? ''));          // LEAD | JOBCARD
$contact_number   = trim($_POST['contact_number']   ?? '');
$other_number     = trim($_POST['other_number']     ?? '');
$alternate_number = trim($_POST['alternate_number'] ?? '');
$area             = trim($_POST['area']             ?? '');
$additional_notes = trim($_POST['additional_notes'] ?? '');
$status           = trim($_POST['status']           ?? '0');
$team_id          = (int) ($_POST['team_id']        ?? 0);

if (!in_array($type, ['LEAD', 'JOBCARD'])) {
    Response::error('Invalid type. Must be LEAD or JOBCARD.');
}
if (!$contact_number) {
    Response::error('Contact number is required.');
}
if (!$area) {
    Response::error('Area / address is required.');
}

// Get next jc_no safely inside a transaction
$db->run('START TRANSACTION');

$max    = (int) $db->scalar('SELECT COALESCE(MAX(jc_no), 0) FROM work_requests FOR UPDATE');
$jc_no  = $max + 1;
$date   = date('Y-m-d H:i');
$userId = (int) $user['user_id'];

if ($type === 'LEAD') {
    // Insert into work_requests only
    $db->run(
        "INSERT INTO work_requests
            (jc_no, type, contact_number, other_number, alternate_number,
             address, user_id, additional_notes, status)
         VALUES (?, 'LEAD', ?, ?, ?, ?, ?, ?, ?)",
        [$jc_no, $contact_number, $other_number, $alternate_number,
         $area, $userId, $additional_notes, $status ?: '0']
    );
    $record_id = (int) $db->lastId();

} else {
    // JOBCARD — insert into work_requests AND jobcards
    if (!$team_id) Response::error('Team is required for a direct Jobcard.');

    $db->run(
        "INSERT INTO work_requests
            (jc_no, type, contact_number, other_number, alternate_number,
             address, user_id, team_id, additional_notes, status)
         VALUES (?, 'JOBCARD', ?, ?, ?, ?, ?, ?, ?, '1')",
        [$jc_no, $contact_number, $other_number, $alternate_number,
         $area, $userId, $team_id, $additional_notes]
    );
    $record_id = (int) $db->lastId();

    $db->run(
        "INSERT INTO jobcards
            (jc_no, date_created, user_id, team_assigned_id,
             contact_number, other_number, alternate_number, address, jc_current_status)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')",
        [$jc_no, $date, $userId, $team_id,
         $contact_number, $other_number, $alternate_number, $area]
    );
}

$db->run('COMMIT');

Response::ok([
    'record_id' => $record_id,
    'jc_no'     => $jc_no,
    'type'      => $type,
], $type === 'LEAD' ? 'Lead created successfully.' : 'Jobcard created and assigned successfully.');