<?php  
require_once __DIR__ . '/../../../config/db.php';
session_start();
include('../../../includes/header.php');  
include('../../../includes/finance_nav.php');   

if (!isset($_SESSION['userName']) || $_SESSION['role'] !== 'finance_second_admin') {
    echo "<script>alert('You must be logged in as a finance second admin to access this page.'); window.location.href = '../../../index.php';</script>";
    exit;
}

// Initialize counts
$doneCount = $pendingCount = $notSeenCount = 0;
$acceptedCount = $pendingForNowCount = $acceptAfterSolutionCount = $delayCount = $rejectedCount = $dependOnYouCount = 0;

try {
    // DONE
    $stmt = $pdo->query("SELECT COUNT(*) FROM submitted_applications WHERE status = 'done'");
    $doneCount = $stmt->fetchColumn();

    // PENDING
    $stmt = $pdo->query("SELECT COUNT(*) FROM submitted_applications WHERE status = 'pending'");
    $pendingCount = $stmt->fetchColumn();

    // NOT SEEN
    $stmt = $pdo->query("SELECT COUNT(*) FROM submitted_applications WHERE status = 'not seen'");
    $notSeenCount = $stmt->fetchColumn();

    // DECISIONS (only ones that were sent to users)
    $stmt = $pdo->query("
        SELECT 
            decision,
            COUNT(*) AS total 
        FROM application_status_updates sau
        JOIN submitted_applications sa ON sau.application_id = sa.id
        WHERE sau.new_receiver = 'user'
        GROUP BY decision
    ");
    $decisions = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $acceptedCount = $decisions['پێشنیازی پەسەنکردن'] ?? 0;
    $pendingForNowCount = $decisions['لەئێستادا ڕابگیرێت'] ?? 0;
    $acceptAfterSolutionCount = $decisions['پێشنیازی پەسەنکردن دوای چارەسەری تێبینی'] ?? 0;
    $delayCount = $decisions['دواخرا بۆ کاتێکی تر'] ?? 0;
    $rejectedCount = $decisions['پێشنیازی ڕەتکردنەوە'] ?? 0;
    $dependOnYouCount = $decisions['لەبەر هەبوونی هەندێک تێبینی بڕیار لای بەڕێزتانە'] ?? 0;

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

try {
    $stmt = $pdo->query("SELECT DISTINCT department FROM users ORDER BY department ASC");
    $departments = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    echo "<option>هەڵە: " . $e->getMessage() . "</option>";
    exit;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
    <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,300;0,400;0,500;0,600;0,700;1,800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="../../../assets/css/layout/base.css?v=2">
    <link rel="stylesheet" href="../../../assets/css/main/cards.css?v=2">
    <link rel="stylesheet" href="../../../assets/css/tables/notificationTable.css?v=2">
    <link rel="stylesheet" href="../../../assets/css/main/searchBox.css?v=2"> 
    <title>داشبۆردی بەڕێوبەراییەتی دارایی</title>
</head>
<body>
<main class="content">
    <div class="align-title">
        <h2>داواکارییەکان</h2>
    </div>
   <section class="sectionLayout extra-padding">
    <div class="card bgAccept" onclick="window.location.href='done_apps.php';">
        داواکاری پەسەندکراو (<?= $doneCount ?>)
    </div>
    <div class="card bgPending" onclick="window.location.href='pending_apps.php';">
        داواکاری هەڵواسراو (<?= $pendingCount ?>)
    </div>
    <div class="card bgOff" onclick="window.location.href='not_seen_apps.php';">
        داواکاری نەبینراو (<?= $notSeenCount ?>)
    </div>
</section>

<div class="align-title">
    <h2>داواکارییەکان</h2>
</div>

<section class="sectionLayout extra-padding">
    <div class="card bgAccept" onclick="window.location.href='accepted_apps.php';">
        داواکاری پەسەندکراو (<?= $acceptedCount ?>)
    </div>
    <div class="card bgPending" onclick="window.location.href='pending_for_now_apps.php';">
        لەئێستادا ڕابگیرێت (<?= $pendingForNowCount ?>)
    </div>
    <div class="card bgAcceptAfterSolution" onclick="window.location.href='accept_after_solution_apps.php';">
        پێشنیازی پەسەنکردن دوای چارەسەری تێبینی (<?= $acceptAfterSolutionCount ?>)
    </div>
    <div class="card bgDependOnYou" onclick="window.location.href='depend_on_you_apps.php';">
        لەبەر هەبوونی هەندێک تێبینی بڕیار لای بەڕێزتانە (<?= $dependOnYouCount ?>)
    </div>
    <div class="card bgdelay" onclick="window.location.href='delay_apps.php';">
        دواخرا بۆ کاتێکی تر (<?= $delayCount ?>)
    </div>
    <div class="card bgReject" onclick="window.location.href='rejected_apps.php';">
        داواکاری ڕەتکراوە (<?= $rejectedCount ?>)
    </div>
</section>
    <hr style="border: 1px solid #ffffff; margin: 20px 0;">
    <div class="align-title-searchBox table__header">
        <h2>ئاگادارکردنەوەکان</h2>
         <!-- Filters in one row -->
  <div class="filter-row">
    <div class="filter-group">
<select class="form-select" id="departmentFilter">
    <option value="all" selected>هەموو بەڕێوبراییەتی</option>
    <?php foreach ($departments as $dept): ?>
        <option value="<?= htmlspecialchars($dept) ?>"><?= htmlspecialchars($dept) ?></option>
    <?php endforeach; ?>
</select>

    </div>
   
  </div>
    </div>
    
    <section class="tableSection">
         <table id="total_app">
                <thead>
                    <tr>
                        <th onclick="sortTable(0)"> ژمارە <i class="fa fa-sort"></i></th>
                        <th onclick="sortTable(1)"> هاتوو <i class="fa fa-sort"></i></th>
                        <th onclick="sortTable(2)"> بابەت  <i class="fa fa-sort"></i></th>
                        <th onclick="sortTable(3)"> بار <i class="fa fa-sort"></i></th>
                        <th onclick="sortTable(4)"> بەروار <i class="fa fa-sort"></i></th>
                        <th onclick="sortTable(5)"> ژمارەی ڕۆژ <i class="fa fa-sort"></i></th>

                        <th style="max-width: 60px;"> زانیاری </th>
    
                    </tr>
                </thead>
          <tbody>
<?php
$send_to = 'بەڕێوبەراییەتی دارایی';

$sql = "
SELECT sa.*, (
    SELECT sau.previous_receiver 
    FROM application_status_updates sau 
    WHERE sau.application_id = sa.id 
    ORDER BY sau.created_at DESC 
    LIMIT 1
) AS previous_receiver
FROM submitted_applications sa
WHERE sa.send_to = :send_to
";

$stmt = $pdo->prepare($sql);

try {
    $stmt->execute(['send_to' => $send_to]);
    $apps = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "<tr><td colspan='7'>Database Error: " . $e->getMessage() . "</td></tr>";
    $apps = [];
}
?>

<?php if (!empty($apps) && is_array($apps)): ?>
    <?php foreach ($apps as $index => $app): ?>
        <?php
            $created_at = new DateTime($app['created_at']);
            $today = new DateTime();
            $diff = $today->diff($created_at)->days;
        ?>
        <tr>
            <td><?= $index + 1 ?></td>
            <td><?= htmlspecialchars($app['previous_receiver'] ?? 'نەدۆزرایەوە') ?></td>
            <td><?= htmlspecialchars($app['subject']) ?></td>
            <td><?= htmlspecialchars($app['status']) ?></td>
            <td><?= $created_at->format('Y-m-d') ?></td>
            <td><?= $diff ?></td>
            <td>
   <button class="info-btn" onclick="window.location.href='view_application.php?id=<?= $app['id'] ?>';">
                    <i class="fa fa-info-circle"></i>
                </button>            </td>
        </tr>
    <?php endforeach; ?>
     <!-- This is the message row when no data is visible after filtering -->
<tr id="noDataRow" style="display: none;">
    <td colspan="8" style="text-align: center; color: red;">هیچ داتایەک نەدۆزرایەوە</td>
</tr>
<?php else: ?>
    <tr><td colspan="7">هیچ داواکاریەک نەگەیشتووە بۆ بەڕێوبەراییەتی دارایی.</td></tr>
<?php endif; ?>

            </tbody>

            </table>
    </section>
</main>

<script src="../../../assets/js/sortButton.js"></script>
<script src="../../../assets/js/activeList.js"></script>
<script src="../../../assets/js/tableFilter.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('departmentFilter').addEventListener('change', applyFilters);
    document.getElementById('decisionFilter').addEventListener('change', applyFilters);
    document.getElementById('statusFilter').addEventListener('change', applyFilters);
});
</script>
</body>
</html>
