<?php
// ─── POST /api/pumps/install-update.php ─────────────────────────────────
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();

$id               = (int)   ($_POST['id']                ?? 0);
$drilling_invoice = trim($_POST['drilling_invoice']      ?? '');
$drilling_team_id = (int)   ($_POST['drilling_team_id']  ?? 0);
$pump_slip        = trim($_POST['pump_slip']              ?? '');
$client_name      = trim($_POST['client_name']            ?? '');
$area             = trim($_POST['area']                   ?? '');
$contact_number   = trim($_POST['contact_number']         ?? '');
$installed_by     = trim($_POST['installed_by']           ?? '');
$attended_by      = trim($_POST['attended_by']            ?? '');
$date_attended    = trim($_POST['date_attended']          ?? '');
$pump_depth       = (int)   ($_POST['pump_depth']         ?? 0);
$cable_meters     = (int)   ($_POST['cable_meters']       ?? 0);
$hdpe_meters      = (int)   ($_POST['hdpe_meters']        ?? 0);
$crack            = (int)   ($_POST['crack']              ?? 0);
$borehole_meters  = (int)   ($_POST['borehole_meters']    ?? 0);
$pack_no          = trim($_POST['pack_no']                ?? '');
$pump_no          = trim($_POST['pump_no']                ?? '');
$map_coords       = trim($_POST['map_co_ordinates']       ?? '');
$problem_desc     = trim($_POST['problem_description']    ?? '');
$problem_sol      = trim($_POST['problem_solution']       ?? '');
$jc_status        = trim($_POST['jc_current_status']      ?? '');
$status           = (int)   ($_POST['status']             ?? 0);
$date_finished    = trim($_POST['date_time_finished']     ?? '');

if (!$id) Response::error('id is required.');

if ($status == 1 && !$date_finished) {
    $date_finished = date('Y-m-d H:i');
}

$db->run(
    "UPDATE pump_installation SET
        drilling_invoice  = ?, drilling_team_id = ?, pump_slip        = ?,
        client_name       = ?, area             = ?, contact_number   = ?,
        installed_by      = ?, attended_by      = ?, date_attended    = ?,
        pump_depth        = ?, cable_meters     = ?, hdpe_meters      = ?,
        crack             = ?, borehole_meters  = ?, pack_no          = ?,
        pump_no           = ?, map_co_ordinates = ?,
        problem_description = ?, problem_solution = ?,
        jc_current_status = ?, status           = ?,
        date_time_finished = ?
     WHERE record_id = ?",
    [$drilling_invoice, $drilling_team_id ?: null, $pump_slip,
     $client_name, $area, $contact_number, $installed_by, $attended_by,
     $date_attended, $pump_depth, $cable_meters, $hdpe_meters,
     $crack, $borehole_meters, $pack_no, $pump_no, $map_coords,
     $problem_desc, $problem_sol, $jc_status, $status,
     $date_finished ?: null, $id]
);

Response::ok(null, 'Installation updated.');