<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/../../config/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../auth/login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];

// Only admin can reopen tickets
if ($role !== 'admin') {
    header("Location: ../issues/?error=unauthorized");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ticket_id'])) {
    $ticket_id = (int) $_POST['ticket_id'];

    // Update status — replace 'open' with a valid ENUM value from your DB
    $new_status = 'open';

    try {
        $stmt = $pdo->prepare("UPDATE tickets SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$new_status, $ticket_id]);

        header("Location: ../issues/?success=reopened");
        exit;
    } catch (PDOException $e) {
        error_log("PDO Error in reopen_ticket.php: " . $e->getMessage());
        header("Location: ../issues/?error=sql_error");
        exit;
    }
} else {
    header("Location: ../issues/?error=invalid_request");
    exit;
}
