<?php
session_start();

header('Content-Type: application/json');  
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

error_reporting(0); ini_set('display_errors', 0);

require_once '../includes/db_config.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin'){
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit;
}

try {
    $database = getDBConnection();

    
    $q1 = "SELECT * FROM notifications WHERE is_read = FALSE ORDER BY created_at DESC LIMIT 10";
    $st1 = $database->prepare($q1); $st1->execute();
    $notifications = $st1->fetchAll(PDO::FETCH_ASSOC);

    $today = date('Y-m-d');  
    $week_start = date('Y-m-d', strtotime('monday this week'));

    $overdue_count = 0; $new_messages = 0; $new_customers = 0; $orders_today = 0;

    $st2 = $database->prepare("SELECT COUNT(*) as cnt FROM orders WHERE status IN ('pending','processing') AND created_at < DATE_SUB(NOW(), INTERVAL 3 DAY)");
    $st2->execute(); $r2 = $st2->fetch(); $overdue_count = $r2 ? (int)$r2['cnt'] : 0;

    $st3 = $database->prepare("SELECT COUNT(*) as cnt FROM contact_messages WHERE status = 'new'");
    $st3->execute(); $r3 = $st3->fetch(); $new_messages = $r3 ? (int)$r3['cnt'] : 0;

    $st4 = $database->prepare("SELECT COUNT(*) as cnt FROM users WHERE DATE(created_at) = ?");
    $st4->execute([$today]); $r4 = $st4->fetch(); $new_customers = $r4 ? (int)$r4['cnt'] : 0;  

    $st5 = $database->prepare("SELECT COUNT(*) as cnt FROM orders WHERE DATE(created_at) = ?");
    $st5->execute([$today]); $r5 = $st5->fetch(); $orders_today = $r5 ? (int)$r5['cnt'] : 0;

    $rt = [];
    if ($overdue_count > 0){
        $rt[] = ['type'=>'warning','title'=>'Overdue Orders','message'=>"There are {$overdue_count} overdue orders that need attention"];
    }
    if ($new_messages > 0){
        $rt[] = ['type'=>'info','title'=>'New Messages','message'=>"You have {$new_messages} new messages from customers"];
    }
    if ($new_customers > 0){
        $rt[] = ['type'=>'success','title'=>'New Customers','message'=>"{$new_customers} new customers registered today"];
    }
    if ($orders_today > 0){
        $rt[] = ['type'=>'info','title'=>'New Orders','message'=>"{$orders_today} new orders received today"];
    }

    $all = array_merge($notifications, $rt);

    echo json_encode(['success'=>true,'notifications'=>$all]);

} catch (PDOException $e){
    echo json_encode(['success'=>false,'error'=>'Database error: '.$e->getMessage()]);
} catch (Exception $e){
    echo json_encode(['success'=>false,'error'=>'Error: '.$e->getMessage()]);
}
?>

