<?php
include 'db.php';

$message = "";

// 1. ප්‍රාදේශීය ලේකම්වරයා නියෝග නිකුත් කිරීම (Issue DS Directive)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'issue_directive') {
    $req_id       = intval($_POST['req_id']);
    $ds_directive = $conn->real_escape_string($_POST['ds_directive']);
    $status       = $conn->real_escape_string($_POST['status']);

    if ($req_id > 0 && !empty($ds_directive)) {
        $sql = "UPDATE change_requests 
                SET ds_directive = '$ds_directive', status = '$status' 
                WHERE id = $req_id";
        if ($conn->query($sql) === TRUE) {
            $message = "<div class='alert success'>නියෝගය සාර්ථකව නිකුත් කරන ලදී! අදාළ අංශයට සහ පරිපාලන නිලධාරීට පෙනෙනු ඇත.</div>";
        } else {
            $message = "<div class='alert error'>දෝෂයක් සිදු විය: " . $conn->error . "</div>";
        }
    }
}

// Category Filter for Performance Modal
$category_filter = isset($_GET['category']) ? $_GET['category'] : '';

// 2. හොඳම නිලධාරීන් 5 දෙනා
$top_sql = "SELECT o.*, d.name as division_name, AVG(f.rating) as avg_rating, COUNT(f.id) as total_feedbacks 
            FROM officers o
            LEFT JOIN divisions d ON o.division_id = d.id
            JOIN feedbacks f ON o.id = f.officer_id
            WHERE o.status = 'ACTIVE'
            GROUP BY o.id HAVING total_feedbacks >= 1
            ORDER BY avg_rating DESC, total_feedbacks DESC LIMIT 5";
$top_officers = $conn->query($top_sql);

// 3. මාණ්ඩලික නිලධාරීන්ගේ ඉල්ලීම් ලැයිස්තුව (Change Requests List)
$requests_sql = "SELECT cr.*, u.officer_title, d.name as division_name 
                 FROM change_requests cr
                 JOIN users u ON cr.user_id = u.id
                 JOIN divisions d ON cr.division_id = d.id
                 ORDER BY cr.status ASC, cr.created_at DESC";
$all_requests = $conn->query($requests_sql);

// 4. අංශ මට්ටමේ සාරාංශය
$div_summary_sql = "SELECT d.name as division_name, COUNT(DISTINCT o.id) as officer_count, COUNT(f.id) as feedback_count, AVG(f.rating) as avg_rating
                    FROM divisions d
                    LEFT JOIN officers o ON d.id = o.division_id AND o.status = 'ACTIVE'
                    LEFT JOIN feedbacks f ON o.id = f.officer_id
                    GROUP BY d.id ORDER BY avg_rating DESC";
$div_summary = $conn->query($div_summary_sql);

// 5. සමස්ත නිලධාරීන් (Modal)
$where = "WHERE o.status = 'ACTIVE'";
if ($category_filter != '') {
    $cat_escaped = $conn->real_escape_string($category_filter);
    $where .= " AND o.category = '$cat_escaped'";
}
$all_officers_sql = "SELECT o.*, d.name as division_name, AVG(f.rating) as avg_rating, COUNT(f.id) as total_feedbacks 
                     FROM officers o
                     LEFT JOIN divisions d ON o.division_id = d.id
                     LEFT JOIN feedbacks f ON o.id = f.officer_id $where
                     GROUP BY o.id ORDER BY avg_rating DESC";
$all_officers = $conn->query($all_officers_sql);

// Chart Data Logic
$current_year  = date('Y');
$current_month = date('m');
$chart_labels = [];
for ($i = 1; $i <= date('j'); $i++) { $chart_labels[] = $i . " වෙනිදා"; }

$divisions_list = $conn->query("SELECT id, name FROM divisions ORDER BY id ASC");
$division_names = [];
while ($d = $divisions_list->fetch_assoc()) { $division_names[$d['id']] = $d['name']; }

$chart_data_sql = "SELECT o.division_id, DAY(f.created_at) as feed_day, AVG(f.rating) as daily_avg
                   FROM feedbacks f JOIN officers o ON f.officer_id = o.id
                   WHERE YEAR(f.created_at) = $current_year AND MONTH(f.created_at) = $current_month
                   GROUP BY o.division_id, DAY(f.created_at)";
$chart_data_result = $conn->query($chart_data_sql);

$daily_ratings = [];
while ($row = $chart_data_result->fetch_assoc()) { $daily_ratings[$row['division_id']][$row['feed_day']] = round($row['daily_avg'], 2); }

$chart_colors = ['#3182ce', '#38a169', '#d69e2e', '#e53e3e', '#805ad5', '#dd6b20', '#319795'];
$datasets = [];
$color_index = 0;
foreach ($division_names as $div_id => $div_name) {
    $data_points = [];
    for ($day = 1; $day <= date('j'); $day++) {
        $data_points[] = isset($daily_ratings[$div_id][$day]) ? $daily_ratings[$div_id][$day] : null;
    }
    $color = $chart_colors[$color_index % count($chart_colors)];
    $datasets[] = ['label' => $div_name, 'data' => $data_points, 'borderColor' => $color, 'backgroundColor' => $color, 'fill' => false, 'tension' => 0.2, 'spanGaps' => true];
    $color_index++;
}
?>

<!DOCTYPE html>
<html lang="si">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ප්‍රාදේශීය ලේකම් ඩෑෂ්බෝඩ් - මාතලේ</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: 'Iskoola Pota', Segoe UI, sans-serif; background: #f0f4f8; margin: 0; padding: 20px; }
        .container { max-width: 1200px; margin: auto; }
        .header { background: #1a365d; color: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; }
        .header h2 { margin: 0; font-size: 22px; }
        
        .leaderboard-card { background: linear-gradient(135deg, #ffffff 0%, #fefcbf 100%); border: 2px solid #d69e2e; padding: 20px; border-radius: 8px; margin-bottom: 25px; box-shadow: 0 4px 10px rgba(0,0,0,0.08); }
        .grid-layout { display: grid; grid-template-columns: 2.1fr 1fr; gap: 20px; margin-bottom: 25px; }
        .card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); margin-bottom: 25px; }

        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 10px; border: 1px solid #e2e8f0; text-align: left; font-size: 13px; }
        th { background: #2b6cb0; color: white; }
        
        .badge-status { padding: 3px 8px; border-radius: 4px; font-weight: bold; font-size: 11px; color: white; }
        .bg-pending { background: #d69e2e; }
        .bg-order { background: #38a169; }
        
        .btn-directive { background: #2b6cb0; color: white; border: none; padding: 5px 10px; border-radius: 4px; font-weight: bold; cursor: pointer; font-size: 12px; }
        .btn-modal { background: #2b6cb0; color: white; border: none; padding: 8px 14px; border-radius: 6px; font-weight: bold; font-size: 13px; cursor: pointer; }
        .nav-link { color: #ebf8ff; text-decoration: none; background: #2b6cb0; padding: 8px 12px; border-radius: 4px; font-weight: bold; font-size: 13px; }

        .alert { padding: 10px; border-radius: 5px; margin-bottom: 15px; font-weight: bold; }
        .success { background: #c6f6d5; color: #22543d; }
        .error { background: #fed7d7; color: #742a2a; }

        /* Modal Styles */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); overflow-y: auto; }
        .modal-content { background: white; width: 500px; margin: 8% auto; padding: 20px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3); }
        .form-group-modal { margin-bottom: 12px; }
        .form-group-modal label { display: block; font-weight: bold; margin-bottom: 4px; font-size: 13px; color: #4a5568; }
        .form-group-modal select, .form-group-modal textarea { width: 100%; padding: 8px; border: 1px solid #cbd5e0; border-radius: 4px; box-sizing: border-box; font-size: 13px; }
    </style>
    <script>
        function openDirectiveModal(id, title, division, type, details, currentDirective) {
            document.getElementById('directive_req_id').value = id;
            document.getElementById('modal_req_info').innerText = title + ' (' + division + ') - ' + type;
            document.getElementById('modal_req_details').innerText = details;
            document.getElementById('ds_directive').value = currentDirective ? currentDirective : '';
            document.getElementById('directiveModal').style.display = 'block';
        }
        function closeDirectiveModal() { document.getElementById('directiveModal').style.display = 'none'; }
        function openOfficerModal() { document.getElementById('officerModal').style.display = 'block'; }
        function closeOfficerModal() { document.getElementById('officerModal').style.display = 'none'; }
    </script>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div>
                <h2>මාතලේ ප්‍රාදේශීය ලේකම් කාර්යාලය</h2>
                <p style="margin: 5px 0 0 0; color: #cbd5e0;">ප්‍රාදේශීය ලේකම් පාලන & කාර්යසාධන ඩෑෂ්බෝඩ් එක</p>
            </div>
            <div>
                <a href="staff_dashboard.php" class="nav-link">🖥️ මාණ්ඩලික ඩෑෂ්බෝඩ්</a>
                <a href="officers_list.php" class="nav-link" style="background: #38a169;">👥 නිලධාරී නාමාවලිය</a>
            </div>
        </div>

        <?php echo $message; ?>

        <!-- 1. මාණ්ඩලික නිලධාරීන්ගේ ඉල්ලීම් & ලේකම් නියෝග කොටස (DS Directives Management) -->
        <div class="card" style="border-top: 4px solid #2b6cb0;">
            <h3 style="margin-top:0; color:#1a365d;">📌 මාණ්ඩලික නිලධාරීන්ගේ ඉල්ලීම් සහ නියෝග නිකුත් කිරීම</h3>
            <table>
                <tr style="background:#1a365d;">
                    <th>දිනය</th>
                    <th>මාණ්ඩලික නිලධාරියා / අංශය</th>
                    <th>ඉල්ලීමේ ස්වභාවය</th>
                    <th>කරුණු / විස්තරය</th>
                    <th>තත්ත්වය</th>
                    <th>ලබාදුන් නියෝගය</th>
                    <th>ක්‍රියාමාර්ග</th>
                </tr>
                <?php if($all_requests->num_rows > 0): ?>
                    <?php while($req = $all_requests->fetch_assoc()): ?>
                    <tr>
                        <td style="font-size:11px;"><?php echo date('Y-m-d h:i A', strtotime($req['created_at'])); ?></td>
                        <td><strong><?php echo $req['officer_title']; ?></strong><br><small style="color:#718096;">(<?php echo $req['division_name']; ?>)</small></td>
                        <td><strong style="color:#2b6cb0;"><?php echo $req['request_type']; ?></strong></td>
                        <td><?php echo htmlspecialchars($req['details']); ?></td>
                        <td>
                            <?php 
                            if($req['status'] == 'PENDING') echo "<span class='badge-status bg-pending'>අලුත් ඉල්ලීමක්</span>";
                            elseif($req['status'] == 'ORDER_ISSUED') echo "<span class='badge-status bg-order'>නියෝග නිකුත් කර ඇත</span>";
                            else echo "<span class='badge-status' style='background:#e53e3e;'>ප්‍රතික්ෂේපිතයි</span>";
                            ?>
                        </td>
                        <td>
                            <?php echo !empty($req['ds_directive']) ? htmlspecialchars($req['ds_directive']) : "<span style='color:#a0aec0;'>-</span>"; ?>
                        </td>
                        <td>
                            <button class="btn-directive" onclick="openDirectiveModal(
                                <?php echo $req['id']; ?>, 
                                '<?php echo addslashes($req['officer_title']); ?>', 
                                '<?php echo addslashes($req['division_name']); ?>', 
                                '<?php echo addslashes($req['request_type']); ?>', 
                                '<?php echo addslashes($req['details']); ?>', 
                                '<?php echo addslashes($req['ds_directive']); ?>'
                            )">
                                ✍️ නියෝග නිකුත් කරන්න
                            </button>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" style="text-align:center; color:#718096;">ඉල්ලීම් කිසිවක් සටහන් වී නැත.</td>
                    </tr>
                <?php endif; ?>
            </table>
        </div>

        <!-- 🏆 හොඳම නිලධාරීන් 5 දෙනා -->
        <div class="leaderboard-card">
            <h3 style="color:#744210; margin-top:0; border-bottom:2px solid #ecc94b; padding-bottom:8px;">🏆 මාසික ඇගයීම සඳහා වූ හොඳම නිලධාරීන් (Top 5 Performers)</h3>
            <table>
                <tr style="background: #f6e05e; color: #744210;">
                    <th>ස්ථානය</th><th>නම</th><th>තනතුර</th><th>අංශය</th><th>ප්‍රතිචාර</th><th>තෘප්ති මට්ටම</th>
                </tr>
                <?php $rank = 1; if($top_officers->num_rows > 0): while($top = $top_officers->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo $rank++; ?></strong></td>
                    <td><strong><?php echo $top['name']; ?></strong></td>
                    <td><?php echo $top['designation']; ?></td>
                    <td><?php echo $top['division_name']; ?></td>
                    <td><?php echo $top['total_feedbacks']; ?></td>
                    <td><strong style="color:#38a169;">⭐ <?php echo number_format($top['avg_rating'], 2); ?> / 5.0</strong></td>
                </tr>
                <?php endwhile; else: echo "<tr><td colspan='6' style='text-align:center;'>ප්‍රතිචාර නැත.</td></tr>"; endif; ?>
            </table>
        </div>

        <!-- Chart & Division Summary -->
        <div class="grid-layout">
            <div class="card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3 style="margin: 0; color: #1a365d;">📈 අංශ මට්ටමේ දෛනික රේටින් ප්‍රස්ථාරය</h3>
                    <button class="btn-modal" onclick="openOfficerModal()">👥 සමස්ත නිලධාරී කාර්යසාධනය</button>
                </div>
                <div style="position: relative; height: 320px;">
                    <canvas id="divisionTrendChart"></canvas>
                </div>
            </div>

            <div class="card">
                <h3 style="margin-top: 0; color: #1a365d;">📊 අංශ මට්ටමේ සාරාංශය</h3>
                <table>
                    <tr><th>අංශය</th><th>නිලධාරීන්</th><th>තෘප්ති මට්ටම</th></tr>
                    <?php while($div = $div_summary->fetch_assoc()): ?>
                    <tr>
                        <td><strong><?php echo $div['division_name']; ?></strong></td>
                        <td><?php echo $div['officer_count']; ?></td>
                        <td><?php echo ($div['feedback_count'] > 0) ? "<strong style='color:#38a169;'>" . number_format($div['avg_rating'], 1) . " / 5</strong>" : "-"; ?></td>
                    </tr>
                    <?php endwhile; ?>
                </table>
            </div>
        </div>

    </div>

    <!-- ලේකම් නියෝග ලබාදෙන Pop-up Modal -->
    <div id="directiveModal" class="modal">
        <div class="modal-content">
            <h3 style="color:#1a365d; margin-top:0; border-bottom:1px solid #e2e8f0; padding-bottom:8px;">✍️ ප්‍රාදේශීය ලේකම් නියෝග නිකුත් කිරීම</h3>
            <form method="POST">
                <input type="hidden" name="action" value="issue_directive">
                <input type="hidden" name="req_id" id="directive_req_id">
                
                <div style="background:#edf2f7; padding:10px; border-radius:5px; margin-bottom:12px; font-size:13px;">
                    <div id="modal_req_info" style="font-weight:bold; color:#2b6cb0;"></div>
                    <div id="modal_req_details" style="margin-top:4px; color:#4a5568;"></div>
                </div>

                <div class="form-group-modal">
                    <label>තත්ත්වය (Status):</label>
                    <select name="status" required>
                        <option value="ORDER_ISSUED">නියෝග නිකුත් කළා (Order Issued)</option>
                        <option value="REJECTED">ප්‍රතික්ෂේප කළා (Rejected)</option>
                    </select>
                </div>

                <div class="form-group-modal">
                    <label>ප්‍රාදේශීය ලේකම්ගේ නියෝගය (DS Directive):</label>
                    <textarea name="ds_directive" id="ds_directive" rows="4" required placeholder="උදා: පරිපාලන නිලධාරී වෙත, අදාළ විෂය සඳහා පවතින අතිරික්තයෙන් නිලධාරියෙකු වහාම අනුයුක්ත කරන්න..."></textarea>
                </div>

                <div style="text-align:right; margin-top:15px;">
                    <button type="button" style="background:#718096; color:white; border:none; padding:8px 14px; border-radius:4px; cursor:pointer;" onclick="closeDirectiveModal()">අවලංගු කරන්න</button>
                    <button type="submit" style="background:#2b6cb0; color:white; border:none; padding:8px 14px; border-radius:4px; font-weight:bold; cursor:pointer;">නියෝගය සුරකින්න</button>
                </div>
            </form>
        </div>
    </div>

    <!-- සමස්ත නිලධාරීන්ගේ Modal -->
    <div id="officerModal" class="modal" style="<?php if(!empty($category_filter)) echo 'display:block;'; ?>">
        <div class="modal-content" style="width:85%; max-width:900px;">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #e2e8f0; padding-bottom:8px; margin-bottom:15px;">
                <h3 style="margin:0; color:#1a365d;">👥 සමස්ත නිලධාරී කාර්යසාධන වාර්තාව</h3>
                <button style="background:#e53e3e; color:white; border:none; padding:5px 10px; border-radius:4px; cursor:pointer;" onclick="closeOfficerModal()">❌ වසන්න</button>
            </div>
            <table>
                <tr><th>නිලධාරියා</th><th>තනතුර</th><th>අංශය / වසම</th><th>ප්‍රතිචාර</th><th>තෘප්ති මට්ටම</th></tr>
                <?php while($row = $all_officers->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo $row['name']; ?></strong></td>
                    <td><?php echo $row['designation']; ?></td>
                    <td><?php echo $row['division_name']; ?></td>
                    <td><?php echo $row['total_feedbacks']; ?></td>
                    <td><?php echo ($row['total_feedbacks'] > 0) ? "<strong style='color:#2b6cb0;'>⭐ " . number_format($row['avg_rating'], 2) . "</strong>" : "-"; ?></td>
                </tr>
                <?php endwhile; ?>
            </table>
        </div>
    </div>

    <script>
        const ctx = document.getElementById('divisionTrendChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: { labels: <?php echo json_encode($chart_labels); ?>, datasets: <?php echo json_encode($datasets); ?> },
            options: { responsive: true, maintainAspectRatio: false, scales: { y: { min: 0, max: 5 } } }
        });
    </script>
</body>
</html>