<?php
/**
 * actions/agency-save.php — POST handler: create or update an agency
 * Super admin only. POST only.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/audit.php';

// POST only
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(base_url('pages/agencies.php'));
}

require_role('super_admin');
csrf_verify();

// ── Inputs ────────────────────────────────────────────────────────────────────

$id            = isset($_POST['id']) && ctype_digit($_POST['id']) ? (int)$_POST['id'] : null;
$name          = trim($_POST['name'] ?? '');
$contact_email = trim($_POST['contact_email'] ?? '');
$phone         = trim($_POST['phone'] ?? '');
$address       = trim($_POST['address'] ?? '');
$notes         = trim($_POST['notes'] ?? '');
$active        = isset($_POST['active']) ? 1 : 0;

// ── Validation ────────────────────────────────────────────────────────────────

$errors = [];

if ($name === '') {
    $errors[] = 'Agency name is required.';
} elseif (mb_strlen($name) > 200) {
    $errors[] = 'Agency name is too long (max 200 characters).';
}

if ($contact_email !== '' && !filter_var($contact_email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Contact email is not a valid email address.';
}

// Check for duplicate name (exclude self on edit)
$dup_sql  = 'SELECT id FROM agencies WHERE name = ?';
$dup_args = [$name];
if ($id) {
    $dup_sql  .= ' AND id != ?';
    $dup_args[] = $id;
}
$dup_stmt = db()->prepare($dup_sql);
$dup_stmt->execute($dup_args);
if ($dup_stmt->fetch()) {
    $errors[] = 'An agency with that name already exists.';
}

if ($errors) {
    set_flash('error', implode(' ', $errors));
    redirect_back(base_url('pages/agencies.php'));
}

// ── Save ──────────────────────────────────────────────────────────────────────

if ($id) {
    // Update
    $stmt = db()->prepare(
        'UPDATE agencies
            SET name = ?, contact_email = ?, phone = ?, address = ?, notes = ?, active = ?
          WHERE id = ?'
    );
    $stmt->execute([$name, $contact_email ?: null, $phone ?: null, $address ?: null, $notes ?: null, $active, $id]);
    audit_log('agency.update', "Updated agency: $name", $id, 'agency');
    set_flash('success', 'Agency updated successfully.');
} else {
    // Insert
    $stmt = db()->prepare(
        'INSERT INTO agencies (name, contact_email, phone, address, notes, active, created_at)
         VALUES (?, ?, ?, ?, ?, 1, NOW())'
    );
    $stmt->execute([$name, $contact_email ?: null, $phone ?: null, $address ?: null, $notes ?: null]);
    $new_id = (int) db()->lastInsertId();
    audit_log('agency.create', "Created agency: $name", $new_id, 'agency');
    set_flash('success', 'Agency created successfully.');
}

redirect(base_url('pages/agencies.php'));
