<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/CustomerService.php';
require_once __DIR__ . '/../../classes/Logger.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$auth->requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$logger    = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$service   = new CustomerService($conn, $logger);
$requestId = (int)($_POST['request_id'] ?? 0);

if (!$requestId) {
    header('Location: index.php');
    exit;
}

if ($auth->isController($_SESSION['user_id'])) {
    // Controllers may only update the delivery/finish date
    $deliveryDate = trim($_POST['delivery_date'] ?? '');
    $note         = trim($_POST['note'] ?? '');
    $service->updateDeliveryDate($requestId, $deliveryDate, $note, $_SESSION['user_id']);
    header('Location: index.php?request_id=' . $requestId . '&success=' . urlencode('Delivery date updated.'));
    exit;
}

// Full update for admin / branch roles
$status     = $_POST['status']     ?? 'open';
$resolution = trim($_POST['resolution'] ?? '');
$note       = trim($_POST['note']       ?? '');
$visibility = $_POST['visibility'] ?? 'internal';
$deliveryDate = trim($_POST['delivery_date'] ?? '');

if ($deliveryDate !== '') {
    $service->updateDeliveryDate($requestId, $deliveryDate, '', $_SESSION['user_id']);
}

if ($service->updateRequest($requestId, $status, $resolution, $note, $visibility, $_SESSION['user_id'])) {
    header('Location: index.php?request_id=' . $requestId . '&success=' . urlencode('Customer service request updated.'));
    exit;
}

header('Location: index.php?success=' . urlencode('No customer service update was made.'));
exit;
