<?php
// ─── POST /api/leads/update.php ──────────────────────────────────────────
// Updates a lead/work_request. If a matching jobcard exists for this jc_no,
// the shared contact fields are synced there too so both tables stay in step.
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

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

$record_id        = (int)   ($_POST['record_id']      ?? 0);
$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']             ?? '');

if (!$record_id) Response::error('record_id is required.');
if ($status === 'ASSIGN TEAM') Response::error('Use the assign endpoint to assign a team.');

// 1. Update work_requests
$db->run(
    "UPDATE work_requests
     SET    contact_number   = ?,
            other_number     = ?,
            alternate_number = ?,
            address          = ?,
            additional_notes = ?,
            status           = ?
     WHERE  record_id = ?",
    [$contact_number, $other_number, $alternate_number,
     $area, $additional_notes, $status, $record_id]
);

// 2. Get the jc_no for this work_request
$jc_no = $db->scalar(
    "SELECT jc_no FROM work_requests WHERE record_id = ?", [$record_id]
);

// 3. If a jobcard row exists for this jc_no, sync the shared contact fields
if ($jc_no) {
    $db->run(
        "UPDATE jobcards
         SET    contact_number   = ?,
                other_number     = ?,
                alternate_number = ?,
                address          = ?
         WHERE  jc_no = ?",
        [$contact_number, $other_number, $alternate_number, $area, $jc_no]
    );
}

Response::ok(null, 'Lead updated successfully.');