<?php
// save_client.php
// Coordinator can VIEW clients.php (read-only role) but must not be able
// to actually write changes — enforced here at the point of any write.
require_once 'includes/auth.php';
require_role(['admin', 'inspector'], true);

require_once 'db.php';
header('Content-Type: application/json');
require_csrf();

$clientId = $_POST['client_id'] ?? null;
$name = trim($_POST['client_name'] ?? '');
$contact = trim($_POST['contact_person'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$email = trim($_POST['email'] ?? '');
$address = trim($_POST['address'] ?? '');

if ($name === '') {
    echo json_encode(['status' => 'error', 'message' => 'Client Name is required.']);
    exit;
}

try {
    if ($clientId) {
        $stmt = $pdo->prepare(
            "UPDATE tbl_clients SET Client_Name = ?, Contact_Person = ?, Phone = ?, Email = ?, Address = ? WHERE ClientID = ?"
        );
        $stmt->execute([$name, $contact, $phone, $email, $address, $clientId]);
    } else {
        $stmt = $pdo->prepare(
            "INSERT INTO tbl_clients (Client_Name, Contact_Person, Phone, Email, Address) VALUES (?, ?, ?, ?, ?)"
        );
        $stmt->execute([$name, $contact, $phone, $email, $address]);
    }

    echo json_encode(['status' => 'success']);
} catch (\PDOException $e) {
    error_log('save_client.php error: ' . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'A database error occurred while saving the client.']);
}
