<?php 

session_start();
if (isset($_SESSION['user_email'])){ 
    
require '../../config.php';
require '../functions.php';	
require '../views/header.view.php';

$connect = connect($database);
if(!$connect){
	header('Location: ./error.php');
	} 

$check_access = check_access($connect);

if ($check_access['user_role'] == 1 || $check_access['user_role'] == 2){

$users_total = users_total($connect); 
$coupons_total = coupons_total($connect);
$coupons = get_latest_coupons($connect);

// Get comprehensive statistics
$stats = [
    'coupons' => $connect->query("SELECT COUNT(*) FROM coupons")->fetchColumn(),
    'active_coupons' => $connect->query("SELECT COUNT(*) FROM coupons WHERE coupon_status = 1")->fetchColumn(),
    'stores' => $connect->query("SELECT COUNT(*) FROM stores")->fetchColumn(),
    'active_stores' => $connect->query("SELECT COUNT(*) FROM stores WHERE store_status = 1")->fetchColumn(),
    'categories' => $connect->query("SELECT COUNT(*) FROM categories")->fetchColumn(),
    'users' => $users_total,
    'subscribers' => $connect->query("SELECT COUNT(*) FROM subscribers")->fetchColumn(),
    'blog_posts' => $connect->query("SELECT COUNT(*) FROM blog_posts")->fetchColumn(),
    'published_posts' => $connect->query("SELECT COUNT(*) FROM blog_posts WHERE post_status = 'published'")->fetchColumn(),
    'pages' => $connect->query("SELECT COUNT(*) FROM pages")->fetchColumn(),
];

// Get recent activity
$recent_coupons = $connect->query("SELECT * FROM coupons ORDER BY coupon_created DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
$recent_stores = $connect->query("SELECT * FROM stores ORDER BY store_id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
$recent_users = $connect->query("SELECT * FROM users ORDER BY user_created DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
$recent_posts = $connect->query("SELECT bp.*, u.user_name FROM blog_posts bp LEFT JOIN users u ON bp.post_author = u.user_id ORDER BY bp.created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// Get monthly stats for chart
$monthly_coupons = $connect->query("
    SELECT DATE_FORMAT(coupon_created, '%Y-%m') as month, COUNT(*) as count 
    FROM coupons 
    WHERE coupon_created >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
    GROUP BY month 
    ORDER BY month
")->fetchAll(PDO::FETCH_ASSOC);

require '../views/home_modern.view.php';

}else{

	header('Location:'.SITE_URL);

}

require '../views/footer.view.php';
    
}else {
		header('Location: ./login.php');		
		}


?>