<?php
include '../db.php';

// Start the session if it's not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Check for admin permissions
if (!isset($_SESSION['mpid']) || $_SESSION['mpid'] !== 1) {
    header("Location: http://localhost/LoanApprovalPredction/admin.php");
    exit();
}

$mpid = $_SESSION['mpid'];
date_default_timezone_set("Asia/Kathmandu");
$date = date("Y-m-d H:i:s");

/**
 * Rule-Based Risk Scoring Algorithm Core
 * Used to aggregate profile metrics for the dashboard summary widget
 */
function evaluateRiskMetric($amount, $reason) {
    $score = 0;

    // 1. Evaluate Amount Exposure
    if ($amount > 100000) {
        $score += 50; 
    } elseif ($amount > 50000) {
        $score += 30;
    } else {
        $score += 10; 
    }

    // 2. Evaluate Purpose Risk Category
    $reasonClean = strtolower(trim($reason));
    $lowRiskReasons = ['education', 'business', 'medical', 'agriculture', 'farming'];
    $medRiskReasons = ['home repair', 'renovation', 'car purchase', 'vehicle', 'investment'];
    
    $matched = false;
    foreach ($lowRiskReasons as $r) {
        if (strpos($reasonClean, $r) !== false) {
            $score += 10;
            $matched = true;
            break;
        }
    }
    if (!$matched) {
        foreach ($medRiskReasons as $r) {
            if (strpos($reasonClean, $r) !== false) {
                $score += 30;
                $matched = true;
                break;
            }
        }
    }
    if (!$matched) {
        $score += 50; // Higher baseline weight for vague or unsupported reasons
    }

    // 3. Map to absolute tier classification
    if ($score >= 80) return 'High';
    if ($score >= 40) return 'Medium';
    return 'Low';
}

// Fetch operational overview numbers
$total_members = 0;
$total_loans_processed = 0;
$pending_loans_count = 0;

$res_m = $conn->query("SELECT COUNT(*) AS total FROM members");
if ($res_m) {
    $row = $res_m->fetch_assoc();
    $total_members = $row['total'];
}

$res_l = $conn->query("SELECT COUNT(*) AS total FROM loan_amount WHERE LoanStatus != 'Pending'");
if ($res_l) {
    $row = $res_l->fetch_assoc();
    $total_loans_processed = $row['total'];
}

$res_p = $conn->query("SELECT COUNT(*) AS total FROM loan_amount WHERE LoanStatus = 'Pending'");
if ($res_p) {
    $row = $res_p->fetch_assoc();
    $pending_loans_count = $row['total'];
}

// Calculate rule engine summary values for pending queue
$high_risk_count = 0;
$med_risk_count = 0;
$low_risk_count = 0;

$risk_query = $conn->query("SELECT LAmount, LoanReason FROM loan_amount WHERE LoanStatus = 'Pending'");
if ($risk_query) {
    while ($loan = $risk_query->fetch_assoc()) {
        $tier = evaluateRiskMetric($loan['LAmount'], $loan['LoanReason']);
        if ($tier === 'High') {
            $high_risk_count++;
        } elseif ($tier === 'Medium') {
            $med_risk_count++;
        } else {
            $low_risk_count++;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="icon" href="../images/Icon.png">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .clock {
            width: 200px;
            height: 200px;
            border: 8px solid #1e293b;
            border-radius: 50%;
            position: relative;
            margin: 0 auto;
            background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
            box-shadow: inset 0 4px 10px rgba(0,0,0,0.1), 0 10px 20px rgba(0,0,0,0.15);
        }
        .outer-clock-face {
            width: 100%;
            height: 100%;
            position: relative;
        }
        .outer-clock-face::after {
            transform: rotate(90deg);
        }
        .outer-clock-face::before,
        .outer-clock-face::after {
            content: '';
            position: absolute;
            width: 4px;
            height: 100%;
            background: #cbd5e1;
            left: 49%;
        }
        .marking {
            background: #94a3b8;
            width: 2px;
            height: 100%;
            position: absolute;
            left: 49.5%;
        }
        .marking-1 { transform: rotate(30deg); }
        .marking-2 { transform: rotate(60deg); }
        .marking-3 { transform: rotate(120deg); }
        .marking-4 { transform: rotate(150deg); }
        
        .clock-center {
            width: 12px;
            height: 12px;
            background: #ef4444;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 10;
        }
        .hand {
            width: 50%;
            background: #1e293b;
            position: absolute;
            top: 50%;
            right: 50%;
            transform-origin: 100%;
            transform: rotate(90deg);
            transition-all: 0.05s;
            transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
            border-radius: 4px;
        }
        .hour-hand {
            height: 5px;
            width: 30%;
            background: #0f172a;
        }
        .minute-hand {
            height: 3px;
            width: 42%;
        }
        .second-hand {
            height: 1.5px;
            background: #ef4444;
            width: 45%;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col justify-between">
    
    <header class="sticky top-0 z-50 shadow-sm">
        <?php include '../includes/newnavbar.php'; ?>
    </header>
    <main class="p-6 flex-grow max-w-7xl mx-auto w-full">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <div class="lg:col-span-2 space-y-6">
                
                <section>
                    <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
                        <span>📊</span> Platform Summary Overview
                    </h2>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div class="bg-white border p-5 rounded-xl shadow-sm hover:shadow-md transition-shadow">
                            <p class="text-sm font-medium text-gray-500 uppercase tracking-wider">Registered Members</p>
                            <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo $total_members; ?></p>
                        </div>
                        <div class="bg-white border p-5 rounded-xl shadow-sm hover:shadow-md transition-shadow">
                            <p class="text-sm font-medium text-gray-500 uppercase tracking-wider">Processed Loans</p>
                            <p class="text-3xl font-bold text-green-600 mt-2"><?php echo $total_loans_processed; ?></p>
                        </div>
                        <div class="bg-white border p-5 rounded-xl shadow-sm hover:shadow-md transition-shadow">
                            <p class="text-sm font-medium text-gray-500 uppercase tracking-wider">Pending Approvals</p>
                            <p class="text-3xl font-bold text-yellow-600 mt-2"><?php echo $pending_loans_count; ?></p>
                        </div>
                    </div>
                </section>

                <section class="bg-white border rounded-xl p-6 shadow-sm">
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center border-b pb-4 mb-4 gap-2">
                        <div>
                            <h2 class="text-lg font-bold text-gray-800 flex items-center gap-2">
                                <span>🛡️</span> Risk Scoring Exposure Summary
                            </h2>
                            <p class="text-xs text-gray-500">Live operational distribution profile of the current pending request queue.</p>
                        </div>
                        <a href="loans.php#pending" class="text-xs font-semibold text-blue-600 hover:underline bg-blue-50 px-2.5 py-1 rounded-md">
                            Audit Queue &rarr;
                        </a>
                    </div>

                    <?php if ($pending_loans_count > 0): ?>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                            <div class="bg-red-50/60 border border-red-100 p-4 rounded-lg flex items-center justify-between">
                                <div>
                                    <span class="text-xs font-bold text-red-700 uppercase tracking-wide">High Risk</span>
                                    <p class="text-2xl font-black text-red-600 mt-1"><?php echo $high_risk_count; ?></p>
                                </div>
                                <span class="text-2xl opacity-75">⚠️</span>
                            </div>

                            <div class="bg-yellow-50/60 border border-yellow-100 p-4 rounded-lg flex items-center justify-between">
                                <div>
                                    <span class="text-xs font-bold text-yellow-700 uppercase tracking-wide">Medium Risk</span>
                                    <p class="text-2xl font-black text-yellow-600 mt-1"><?php echo $med_risk_count; ?></p>
                                </div>
                                <span class="text-2xl opacity-75">⚡</span>
                            </div>

                            <div class="bg-green-50/60 border border-green-100 p-4 rounded-lg flex items-center justify-between">
                                <div>
                                    <span class="text-xs font-bold text-green-700 uppercase tracking-wide">Low Risk</span>
                                    <p class="text-2xl font-black text-green-600 mt-1"><?php echo $low_risk_count; ?></p>
                                </div>
                                <span class="text-2xl opacity-75">✅</span>
                            </div>
                        </div>

                        <div class="mt-6">
                            <p class="text-xs font-semibold text-gray-500 mb-2">Queue Composition Percentage</p>
                            <div class="w-full h-3 rounded-full overflow-hidden flex bg-gray-200">
                                <?php
                                $hp = ($high_risk_count / $pending_loans_count) * 100;
                                $mp = ($med_risk_count / $pending_loans_count) * 100;
                                $lp = ($low_risk_count / $pending_loans_count) * 100;
                                ?>
                                <div style="width: <?php echo $hp; ?>%" class="bg-red-500 h-full transition-all" title="High Risk"></div>
                                <div style="width: <?php echo $mp; ?>%" class="bg-yellow-400 h-full transition-all" title="Medium Risk"></div>
                                <div style="width: <?php echo $lp; ?>%" class="bg-green-500 h-full transition-all" title="Low Risk"></div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-6 text-gray-400 text-sm">
                            No pending requests in the system pipeline to classify.
                        </div>
                    <?php endif; ?>
                </section>
            </div>

            <div class="bg-white border rounded-xl p-6 shadow-sm flex flex-col justify-between items-center">
                <h3 class="text-sm font-bold text-gray-700 uppercase tracking-wide mb-4 text-center w-full border-b pb-2">
                    System Watch
                </h3>
                
                <div class="clock">
                    <div class="outer-clock-face">
                        <div class="marking marking-1"></div>
                        <div class="marking marking-2"></div>
                        <div class="marking marking-3"></div>
                        <div class="marking marking-4"></div>
                    </div>
                    <div class="hand hour-hand"></div>
                    <div class="hand minute-hand"></div>
                    <div class="hand second-hand"></div>
                    <div class="clock-center"></div>
                </div>

                <div class="mt-6 text-center">
                    <p class="text-xs font-medium text-gray-400 uppercase tracking-wider">Server Local Timestamp</p>
                    <p class="text-sm font-mono font-bold text-gray-700 bg-gray-100 px-3 py-1.5 rounded-lg mt-1.5 border">
                        <?php echo htmlspecialchars($date, ENT_QUOTES, 'UTF-8'); ?>
                    </p>
                </div>
            </div>

        </div>
    </main>

    <footer class="border-t bg-white text-center text-xs text-gray-400 py-4 mt-8">
        <p>&copy; <?php echo date("Y"); ?> Loan Approval Prediction. All administrative access logged.</p>
    </footer>

    <script>
        function updateClock() {
            const now = new Date();
            const seconds = now.getSeconds();
            const minutes = now.getMinutes();
            const hours = now.getHours() % 12 || 12;

            const secondsDegrees = (seconds / 60) * 360 + 90;
            const minutesDegrees = (minutes / 60) * 360 + (seconds / 60) * 6 + 90;
            const hoursDegrees = (hours / 12) * 360 + (minutes / 60) * 30 + 90;

            document.querySelector('.second-hand').style.transform = `rotate(${secondsDegrees}deg)`;
            document.querySelector('.minute-hand').style.transform = `rotate(${minutesDegrees}deg)`;
            document.querySelector('.hour-hand').style.transform = `rotate(${hoursDegrees}deg)`;
        }

        setInterval(updateClock, 1000);
        updateClock(); // Initial instant tick execution
    </script>
</body>
</html>