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

// Check if user is finance_second_admin
if ($_SESSION['role'] !== 'finance_second_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']);
$updated_by = $_SESSION['email'];

$valid_targets = ['یاریدەدەری سەرۆکی زانکۆ', 'user'];

if (!in_array($reassigned_to, $valid_targets)) {
    die("بەڕێوەبەرایەتی دارایی تەنها دەتوانێت بۆ یاریدەدەری سەرۆکی زانکۆ یان بەکارهێنەر نێردرێت.");
}

$new_status = ($reassigned_to === 'user') ? 'done' : 'pending';

try {
    // 1. Get current receiver
    $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
    $logStmt = $pdo->prepare("INSERT INTO application_status_updates 
        (application_id, previous_receiver, new_receiver, decision, comment, updated_by)
        VALUES (?, ?, ?, ?, ?, ?)");
    $logStmt->execute([ 
        $application_id,
        $previous_receiver,
        $reassigned_to,
        $decision,
        $comment,
        $updated_by
    ]);

    // 3. Update application
    $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/finance_second_admin/finance_second_admin_dashboard.php?success=1");
    exit;

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