<?php
// ─── POST /api/leads/assign.php ──────────────────────────────────────────
// Assigns a team to a lead — converts it into a live jobcard.
//
// What happens:
//   1. work_requests row → type='JOBCARD', team_id=X, status='1'
//   2. New row inserted into jobcards (jc_current_status='PENDING')
//
// This mirrors exactly what the original assign_jobcard.ajax.php does.

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();

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

if (!$record_id) Response::error('record_id is required.');
if (!$team_id)   Response::error('A team must be selected.');
if (!$area)      Response::error('Area / address is required.');

// Fetch the work_request to get jc_no
$lead = $db->row(
    "SELECT * FROM work_requests WHERE record_id = ?",
    [$record_id]
);

if (!$lead) Response::error('Lead not found.', 404);
if ($lead['status'] === '1') Response::error('This lead has already been assigned.');

$jc_no  = (int) $lead['jc_no'];
$date   = date('Y-m-d H:i');
$userId = (int) $user['user_id'];

$db->run('START TRANSACTION');

// 1. Update work_requests — mark as JOBCARD / assigned
$db->run(
    "UPDATE work_requests
     SET    type             = 'JOBCARD',
            contact_number   = ?,
            other_number     = ?,
            alternate_number = ?,
            address          = ?,
            user_id          = ?,
            team_id          = ?,
            additional_notes = ?,
            status           = '1'
     WHERE  record_id = ?",
    [$contact_number, $other_number, $alternate_number,
     $area, $userId, $team_id, $additional_notes, $record_id]
);

// 2. Insert into jobcards — the live drilling jobcard
$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]
);

$jobcard_id = (int) $db->lastId();

$db->run('COMMIT');

// Get team name for response
$team = $db->row("SELECT name FROM teams WHERE record_id = ?", [$team_id]);

Response::ok([
    'jc_no'      => $jc_no,
    'jobcard_id' => $jobcard_id,
    'team_name'  => $team['name'] ?? '',
], "JC #{$jc_no} assigned to {$team['name']}. Jobcard created.");