<?php 
require_once '../config/db.php';
session_start();

// Check if user is dean_admin
if ($_SESSION['role'] !== 'dean_admin') {
    die("Unauthorized access.");
}

// Validate POST input
if (!isset($_POST['application_id'], $_POST['decision'], $_POST['comment'], $_POST['status'], $_POST['reassigned_to'])) {
    die("Missing data.");
}

$application_id = (int) $_POST['application_id'];
$decision = trim($_POST['decision']);
$comment = trim($_POST['comment']);
$current_status = $_POST['status'];
$reassigned_to = trim($_POST['reassigned_to']);

// Only allow sending to assistant_first_admin
if ($reassigned_to !== 'یاریدەدەری سەرۆکی زانکۆ') {
    die("داواکاری تەنها دەتوانرێت بۆ یاریدەدەری سەرۆکی زانکۆ نێردرێت.");
}

$new_status = ($reassigned_to === 'یاریدەدەری سەرۆکی زانکۆ') ? 'pending' : $current_status;

try {
    // 1. Get current receiver from application
    $stmt = $pdo->prepare("SELECT send_to FROM submitted_applications WHERE id = ?");
    $stmt->execute([$application_id]);
    $previous_receiver = $stmt->fetchColumn();

    // 2. Insert into application_status_updates log
    $insertLog = $pdo->prepare("INSERT INTO application_status_updates 
        (application_id, previous_receiver, new_receiver, decision, comment, updated_by)
        VALUES (?, ?, ?, ?, ?, ?)");
    $insertLog->execute([
        $application_id,
        $previous_receiver,
        $reassigned_to,
        $decision,
        $comment,
        $_SESSION['email']
    ]);

    // 3. Update the main submitted_applications table
    $stmt = $pdo->prepare("UPDATE submitted_applications SET status = ?,  send_to = ?, sent_by = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
    $stmt->execute([$new_status,  $reassigned_to, 'سەرۆکی زانکۆ', $application_id]);

    header("Location: /ProcurementRequestSystem/pages/admins/dean_admin/dean_admin_dashboard.php?success=1");
    exit;

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}
?>
