<?php
require_once __DIR__ . '/../../config/db.php';

session_start();
include('../../includes/header.php');  
include('../../includes/nav.php');  

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'user') {
    header('Location: ../../index.php');
    exit;
}

$user_id = $_SESSION['user_id'];

$total_count = 0; 

$sql = "SELECT COUNT(*) AS total_count FROM submitted_applications WHERE user_id = :user_id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);

try {
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($result) {
        $total_count = $result['total_count']; 
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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 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/totalAppTable.css?v=2">
    <link rel="stylesheet" href="../../assets/css/main/searchBox.css?v=2">


    <title>داشبۆردی ڕاگر</title>
    <style>
    


    </style>
</head>
<body>

    <main class="content">
        <div class="align-title-searchBox table__header">
        <h2>کۆی گشتی داواکاری نێردراو         <strong><?php echo $total_count; ?></strong>
        </h2>         
             <!-- Filters in one row -->
  <div class="filter-row">

    <div class="filter-group">
<select class="form-select" id="decisionFilter">
    <option value="all" selected>بڕیار</option>
 <option value="پێشنیازی پەسەنکردن">پێشنیازی پەسەنکردن</option>
        <option value="پێشنیازی ڕەتکردنەوە">پێشنیازی ڕەتکردنەوە</option>
        <option value="لەئێستادا ڕابگیرێت">لەئێستادا ڕابگیرێت</option>
        <option value="پێشنیازی پەسەنکردن دوای چارەسەری تێبینی">پێشنیازی پەسەنکردن دوای چارەسەری تێبینی</option>
        <option value="لەبەر هەبوونی هەندێک تێبینی بڕیار لای بەڕێزتانە">لەبەر هەبوونی هەندێک تێبینی بڕیار لای بەڕێزتانە</option>
        <option value="دواخرا بۆ کاتێکی تر">دواخرا بۆ کاتێکی تر</option>
</select>

    </div>
        <div class="filter-group">
<select class="form-select" id="statusFilter">
    <option value="all" selected>بار</option>
    <option value="not seen">نوێ</option>
    <option value="pending">چاوەڕوان</option>
    <option value="done">تەواو</option>
</select>

    </div>
  </div>
          </div>
        <section class="table__body">
            <table id="total_app" class="styled-table">
            <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
                try {
                    $query = $_GET['query'] ?? '';
                    $column = $_GET['column'] ?? 'all';

$sql = "
SELECT sa.*, sau.decision, sau.previous_receiver
FROM submitted_applications sa
LEFT JOIN (
    SELECT application_id, decision, previous_receiver
    FROM application_status_updates
    WHERE id IN (
        SELECT MAX(id)
        FROM application_status_updates
        GROUP BY application_id
    )
) sau ON sa.id = sau.application_id
WHERE sa.user_id = :user_id
ORDER BY sa.created_at DESC
";



                    $params = ['user_id' => $user_id];

                    if (!empty($query)) {
                        if ($column === 'all') {
                            $sql .= " AND (sa.sent_by LIKE :q OR sa.subject LIKE :q OR sa.status LIKE :q)";
                            $params['q'] = '%' . $query . '%';
                        } elseif (in_array($column, ['sent_by', 'subject', 'status'])) {
                            $sql .= " AND sa.$column LIKE :q";
                            $params['q'] = '%' . $query . '%';
                        }
                    }

                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $apps = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    if (count($apps) === 0) {
                        echo "<tr><td colspan='8'>هیچ داتایەک نەدۆزرایەوە.</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['previous_receiver'] ?? 'یاریدەدەری سەرۆکی زانکۆ') . "</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='8'>هەڵە لە هێنانی داتا: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
                }
                ?>
            </tbody>
</tbody>
            </table>
         
      </section>
    </main>


    <script src="../../assets/js/sortButton.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>
