<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$role_id = $_SESSION['role_id'];
if (!in_array($role_id, [1, 2])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Forbidden']);
    exit;
}

try {
    $pdo = getDB();

    // Today sales total
    $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) FROM sales_invoices WHERE DATE(invoice_date) = CURDATE() AND invoice_status != 'Cancelled'");
    $today_sales = (float)$stmt->fetchColumn();

    // Today repair income (payments where type=repair today)
    $stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM payments WHERE payment_type = 'repair' AND DATE(payment_date) = CURDATE()");
    $today_repair_income = (float)$stmt->fetchColumn();

    // Pending repairs
    $stmt = $pdo->query("SELECT COUNT(*) FROM repair_jobs WHERE repair_status NOT IN ('Delivered','Cancelled','Cannot Repair')");
    $pending_repairs = (int)$stmt->fetchColumn();

    // Completed repairs (Delivered)
    $stmt = $pdo->query("SELECT COUNT(*) FROM repair_jobs WHERE repair_status = 'Delivered'");
    $completed_repairs = (int)$stmt->fetchColumn();

    // Low stock products
    $stmt = $pdo->query("SELECT COUNT(*) FROM products WHERE current_stock <= low_stock_qty AND status = 1");
    $low_stock = (int)$stmt->fetchColumn();

    // Total customers
    $stmt = $pdo->query("SELECT COUNT(*) FROM customers WHERE status = 1");
    $total_customers = (int)$stmt->fetchColumn();

    // Total products
    $stmt = $pdo->query("SELECT COUNT(*) FROM products WHERE status = 1");
    $total_products = (int)$stmt->fetchColumn();

    // Total invoices
    $stmt = $pdo->query("SELECT COUNT(*) FROM sales_invoices WHERE invoice_status != 'Cancelled'");
    $total_invoices = (int)$stmt->fetchColumn();

    // Today purchases count
    $stmt = $pdo->query("SELECT COUNT(*) FROM purchases WHERE DATE(purchase_date) = CURDATE()");
    $today_purchases = (int)$stmt->fetchColumn();

    // Supplier due
    $stmt = $pdo->query("SELECT COALESCE(SUM(current_balance), 0) FROM suppliers WHERE status = 1");
    $supplier_due = (float)$stmt->fetchColumn();

    // Customer due
    $stmt = $pdo->query("SELECT COALESCE(SUM(current_balance), 0) FROM customers WHERE status = 1");
    $customer_due = (float)$stmt->fetchColumn();

    // Today expenses
    $stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE DATE(expense_date) = CURDATE()");
    $today_expenses = (float)$stmt->fetchColumn();

    // Net profit estimate (today's sales gross profit + today repair income - today expenses)
    $stmt = $pdo->query("SELECT COALESCE(SUM(sii.total_price - (sii.cost_price * sii.quantity)), 0) FROM sales_invoice_items sii JOIN sales_invoices si ON sii.sales_invoice_id = si.id WHERE si.invoice_status != 'Cancelled' AND DATE(si.invoice_date) = CURDATE()");
    $today_sales_profit = (float)$stmt->fetchColumn();

    $net_profit = $today_sales_profit + $today_repair_income - $today_expenses;

    // Recent sales (last 10)
    $stmt = $pdo->query("SELECT si.id, si.invoice_no, si.total_amount, si.paid_amount, si.due_amount, si.payment_status, si.invoice_date, COALESCE(c.name, 'Walk-in') as customer_name FROM sales_invoices si LEFT JOIN customers c ON si.customer_id = c.id WHERE si.invoice_status != 'Cancelled' ORDER BY si.id DESC LIMIT 10");
    $recent_sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Recent repairs (last 10)
    $stmt = $pdo->query("SELECT rj.id, rj.job_no, rj.repair_status, rj.final_amount, rj.created_at, COALESCE(c.name, '-') as customer_name FROM repair_jobs rj LEFT JOIN customers c ON rj.customer_id = c.id ORDER BY rj.id DESC LIMIT 10");
    $recent_repairs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Low stock products detail
    $stmt = $pdo->query("SELECT id, product_name, current_stock, low_stock_qty FROM products WHERE current_stock <= low_stock_qty AND status = 1 ORDER BY current_stock ASC LIMIT 10");
    $low_stock_products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Repair status chart
    $stmt = $pdo->query("SELECT repair_status as status, COUNT(*) as count FROM repair_jobs GROUP BY repair_status ORDER BY count DESC");
    $repair_status_chart = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Monthly sales chart
    $stmt = $pdo->prepare("SELECT MONTH(invoice_date) as month, COALESCE(SUM(total_amount), 0) as total FROM sales_invoices WHERE YEAR(invoice_date) = ? AND invoice_status != 'Cancelled' GROUP BY MONTH(invoice_date) ORDER BY month");
    $stmt->execute([date('Y')]);
    $monthly_sales_chart = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'stats' => [
            'today_sales' => $today_sales,
            'today_repair_income' => $today_repair_income,
            'pending_repairs' => $pending_repairs,
            'completed_repairs' => $completed_repairs,
            'low_stock' => $low_stock,
            'total_customers' => $total_customers,
            'total_products' => $total_products,
            'total_invoices' => $total_invoices,
            'today_purchases' => $today_purchases,
            'supplier_due' => $supplier_due,
            'customer_due' => $customer_due,
            'today_expenses' => $today_expenses,
            'net_profit' => $net_profit,
        ],
        'recent_sales' => $recent_sales,
        'recent_repairs' => $recent_repairs,
        'low_stock_products' => $low_stock_products,
        'repair_status_chart' => $repair_status_chart,
        'monthly_sales_chart' => $monthly_sales_chart,
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
