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

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

$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    // Redirect or handle not logged in user
    header("Location: ../../index.php");
    exit;
}

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

try {
    // DONE
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM submitted_applications WHERE user_id = ? AND status = 'done'");
    $stmt->execute([$user_id]);
    $doneCount = $stmt->fetchColumn();

    // PENDING
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM submitted_applications WHERE user_id = ? AND status = 'pending'");
    $stmt->execute([$user_id]);
    $pendingCount = $stmt->fetchColumn();

    // NOT SEEN
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM submitted_applications WHERE user_id = ? AND status = 'not seen'");
    $stmt->execute([$user_id]);
    $notSeenCount = $stmt->fetchColumn();

    // DECISION COUNTS (from status updates)
    $stmt = $pdo->prepare("
        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' AND sa.user_id = ?
        GROUP BY decision
    ");
    $stmt->execute([$user_id]);
    $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();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <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>
    <style>
        .search-box {
            margin: 0 auto;
        }

        .search-box input[type="text"] {
            padding: 8px;
            width: 200px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-box button {
            padding: 8px 12px;
            font-size: 14px;
            border: 1px solid #ccc;
            background-color: #eee;
            border-radius: 4px;
            cursor: pointer;
        }

        .search-box button:hover {
            background-color: #ddd;
        }
    </style>
</head>
<body>

<main class="content">

    <section class="sectionLayout extra-padding">
        <button class="card bgSend" onclick="window.location.href='submit_application.php';">ناردنی داواکاری</button>
        <button class="card borderColor" onclick="window.location.href='uploaded_files.php';">فایلی بارکراو</button>
    </section>

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

    <section class="sectionLayout extra-padding">
        <div class="card bgAccept" onclick="window.location.href='done_apps.php';">
            داواکاری کۆتاهاتوو (<span><?= $doneCount ?></span>)
        </div>
        <div class="card bgPending" onclick="window.location.href='pending_apps.php';">
            داواکاری هەڵواسراو (<span><?= $pendingCount ?></span>)
        </div>
        <div class="card bgOff" onclick="window.location.href='not_seen_apps.php';">
            داواکاری نەبینراو (<span><?= $notSeenCount ?></span>)
        </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';">
            پێشنیازی پەسەندکردن (<span><?= $acceptedCount ?></span>)
        </div>
        <div class="card bgPending" onclick="window.location.href='pending_for_now_apps.php';">
            لەئێستادا ڕابگیرێت (<span><?= $pendingForNowCount ?></span>)
        </div>
        <div class="card bgAcceptAfterSolution" onclick="window.location.href='accept_after_solution_apps.php';">
            پێشنیازی پەسەنکردن دوای چارەسەری تێبینی (<span><?= $acceptAfterSolutionCount ?></span>)
        </div>
        <div class="card bgdelay" onclick="window.location.href='delay_apps.php';">
            دواخرا بۆ کاتێکی تر (<span><?= $delayCount ?></span>)
        </div>
        <div class="card bgReject" onclick="window.location.href='rejected_apps.php';">
            پێشنیازی ڕەتکردنەوە (<span><?= $rejectedCount ?></span>)
        </div>
        <div class="card bgDependOnYou" onclick="window.location.href='depend_on_you_apps.php';">
            لەبەر هەبوونی تێبینی بڕیار لای بەڕێزتانە (<span><?= $dependOnYouCount ?></span>)
        </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="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="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
        try {
            $query = $_GET['query'] ?? '';
            $column = $_GET['column'] ?? 'all';

            $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.user_id = :user_id
            ORDER BY sa.created_at DESC
            ";

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

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $apps = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo "<tr><td colspan='7'>هەڵە لە هێنانی داتا: " . htmlspecialchars($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; ?>
            <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>
  setTimeout(() => {
    const alertBox = document.querySelector('.custom-alert');
    if (alertBox) {
      alertBox.style.opacity = '0';
      setTimeout(() => alertBox.remove(), 1000);
    }
  }, 4000);
</script>

<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>
