<?php

session_start();

include("../config/db.php");

header('Content-Type: application/json');

if($_SERVER['REQUEST_METHOD'] != 'POST'){

    echo json_encode([
        'success' => false
    ]);

    exit;

}

$contract_id = isset($_POST['contract_id'])
    ? intval($_POST['contract_id'])
    : 0;

$status = isset($_POST['status'])
    ? trim($_POST['status'])
    : '';

if(!$contract_id || empty($status)){

    echo json_encode([
        'success' => false
    ]);

    exit;

}

$status_safe = $conn->real_escape_string($status);

$exists = $conn->query("
SELECT id
FROM pipeline_status
WHERE contract_id = '$contract_id'
LIMIT 1
");

if($exists->num_rows > 0){

    $conn->query("
    UPDATE pipeline_status
    SET
        status_name = '$status_safe',
        updated_at = NOW()
    WHERE contract_id = '$contract_id'
    ");

}else{

    $conn->query("
    INSERT INTO pipeline_status (
        contract_id,
        status_name
    ) VALUES (
        '$contract_id',
        '$status_safe'
    )
    ");

}

/*
|--------------------------------------------------------------------------
| ACTUALIZAR ESTADO EN CONTRACTS
|--------------------------------------------------------------------------
*/

$conn->query("
UPDATE contracts
SET contract_status = '$status_safe'
WHERE id = '$contract_id'
");

echo json_encode([
    'success' => true
]);