<?php
/**
 * Edit Ticket API
 * 
 * Allows admins to edit tickets and add responses
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication
requireAdmin(true);

// Load configuration and database connection
require_once 'config.php';
require_once 'db.php';

$data = json_decode(file_get_contents('php://input'), true);

// Basic validation
if (!isset($data['id'])) {
    http_response_code(400);
    echo json_encode(["success" => false, "error" => "Missing ticket ID"]);
    exit;
}

// Get admin ID from session; require a valid admin session
$admin_id = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 0;
if ($admin_id <= 0) {
    http_response_code(401);
    echo json_encode(["success" => false, "error" => "Admin session required"]);
    exit;
}

// Determine if this is an edit or a response
$isResponse = isset($data['response']) && !empty(trim($data['response']));

try {
    // Begin transaction for data integrity
    $pdo->beginTransaction();
    
    if ($isResponse) {
        // This is a response - add response and update status if provided
        $sql = "UPDATE tickets SET response = ?, response_at = NOW(), admin_id = ?";
        $params = [$data['response'], $admin_id];
        
        // If status is provided, update it
        if (isset($data['status']) && !empty($data['status'])) {
            $sql .= ", status = ?";
            $params[] = $data['status'];
        }
        
        $sql .= " WHERE id = ?";
        $params[] = $data['id'];
        
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute($params);
        
        // Log admin response
        try {
            $logStmt = $pdo->prepare('INSERT INTO admin_logs (admin_id, action, entity_type, entity_id, details, created_at) 
                VALUES (?, ?, ?, ?, ?, NOW())');
            $logStmt->execute([
                $admin_id,
                'respond',
                'ticket',
                $data['id'],
                json_encode(['status' => $data['status'] ?? null])
            ]);
        } catch (Exception $e) {
            // Log the error but continue with the main operation
            error_log('Failed to log admin ticket response: ' . $e->getMessage());
        }
    } else {
        // This is a general edit - update all fields
        $stmt = $pdo->prepare("UPDATE tickets SET subject = ?, message = ?, status = ? WHERE id = ?");
        $result = $stmt->execute([
            $data['subject'] ?? '',
            $data['message'] ?? '',
            $data['status'] ?? 'open',
            $data['id']
        ]);
        
        // Log admin edit
        try {
            $logStmt = $pdo->prepare('INSERT INTO admin_logs (admin_id, action, entity_type, entity_id, details, created_at) 
                VALUES (?, ?, ?, ?, ?, NOW())');
            $logStmt->execute([
                $admin_id,
                'edit',
                'ticket',
                $data['id'],
                json_encode(['status' => $data['status'] ?? null])
            ]);
        } catch (Exception $e) {
            // Log the error but continue with the main operation
            error_log('Failed to log admin ticket edit: ' . $e->getMessage());
        }
    }
    
    // Commit the transaction
    $pdo->commit();
    
    echo json_encode(["success" => true]);
} catch (Exception $e) {
    // Rollback on error
    $pdo->rollBack();
    
    http_response_code(500);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
