<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../config/db.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $application_id = $_POST['application_id'];
    $decision = $_POST['decision'];
    $comment = $_POST['comment'];
    $new_receiver = $_POST['reassigned_to'];
    $updated_by = $_SESSION['email']; // or role if you prefer
    $status = ($new_receiver === 'user') ? 'done' : 'pending';

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

    // 2. Insert status update 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,
        $new_receiver,
        $decision,
        $comment,
        $updated_by
    ]);

    // 3. Update main application table
    $updateApp = $pdo->prepare("UPDATE submitted_applications 
        SET send_to = ?, status = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?");
    $updateApp->execute([
        $new_receiver,
        $status,
        $application_id
    ]);

    header("Location: ../pages/admins/assistant_first_admin/assistant_first_admin_dashboard.php");
    exit;
}

// Fetch applications based on send_by or send_to
try {
    $email = $_SESSION['email'];
    
    // Fetch applications where the current admin is the sender (sent_by) or receiver (send_to)
    $stmt = $pdo->prepare("SELECT * FROM submitted_applications WHERE sent_by = :sent_by OR send_to = :send_to");
    $stmt->execute([
        'sent_by' => $email,
        'send_to' => 'یاریدەدەری سەرۆکی زانکۆ' // Adjust this value for your specific role check
    ]);
    $apps = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($apps)) {
        echo "<tr><td colspan='7'>هیچ داواکاریەک نەگەیشتووە بۆ یاریدەدەری سەرۆکی یەکەم.</td></tr>";
    } else {
        foreach ($apps as $index => $app) {
            $created_at = new DateTime($app['created_at']);
            $today = new DateTime();
            $diff = $today->diff($created_at)->days;

            echo "<tr>";
            echo "<td>" . ($index + 1) . "</td>";
            echo "<td>" . htmlspecialchars($app['sent_by']) . "</td>";
            echo "<td>" . htmlspecialchars($app['subject']) . "</td>";
            echo "<td>" . htmlspecialchars($app['status']) . "</td>";
            echo "<td>" . $created_at->format('Y-m-d') . "</td>";
            echo "<td>" . $diff . "</td>";
            echo "<td><a href='view_application.php?id=" . $app['id'] . "'>وردەکاری</a></td>";
            echo "</tr>";
        }
    }
} catch (PDOException $e) {
    echo "<tr><td colspan='7'>هەڵە لە هێنانی داتا: " . $e->getMessage() . "</td></tr>";
}
?>
