<?php
namespace App\Modules\Dashboard\Controllers;

use Core\Controller;
use Core\Auth;

class DashboardController extends Controller {
    public function index() {
        $this->requireAuth();

        if (Auth::isSuperAdmin()) {
            return $this->superAdminDashboard();
        } elseif (Auth::isContractorUser()) {
            return $this->contractorDashboard();
        } else {
            return $this->orgDashboard();
        }
    }

    public function orgDashboard() {
        $this->requireAuth();
        $user  = Auth::user();
        $orgId = Auth::orgId();

        $totalProjects      = $this->dbQueryOne("SELECT COUNT(*) as cnt FROM projects WHERE org_id = ?", [$orgId])['cnt'] ?? 0;
        $activeProjects     = $this->dbQueryOne("SELECT COUNT(*) as cnt FROM projects WHERE org_id = ? AND status = 'active'", [$orgId])['cnt'] ?? 0;
        $totalContractors   = $this->dbQueryOne("SELECT COUNT(*) as cnt FROM contractors WHERE org_id = ? AND is_approved = 1", [$orgId])['cnt'] ?? 0;
        $totalInvoiceAmount = $this->dbQueryOne("SELECT COALESCE(SUM(total_amount),0) as total FROM invoices WHERE org_id = ? AND status = 'paid'", [$orgId])['total'] ?? 0;

        $recentProjects      = $this->dbQuery("SELECT * FROM projects WHERE org_id = ? ORDER BY created_at DESC LIMIT 5", [$orgId]);
        $pendingInvoices     = $this->dbQuery(
            "SELECT i.*, c.company_name as contractor_name FROM invoices i LEFT JOIN contractors c ON i.contractor_id = c.id WHERE i.org_id = ? AND i.status IN ('submitted','under_review') ORDER BY i.created_at DESC LIMIT 5",
            [$orgId]
        );
        $upcomingMilestones  = $this->dbQuery(
            "SELECT pm.*, p.name as project_name FROM project_milestones pm JOIN projects p ON pm.project_id = p.id WHERE p.org_id = ? AND pm.status != 'completed' ORDER BY pm.due_date ASC LIMIT 5",
            [$orgId]
        );
        $recentActivity      = $this->dbQuery(
            "SELECT al.*, CONCAT(u.first_name, ' ', u.last_name) as user_name
             FROM audit_logs al LEFT JOIN users u ON al.user_id = u.id
             WHERE al.org_id = ? ORDER BY al.created_at DESC LIMIT 8",
            [$orgId]
        );
        foreach ($recentActivity as &$activity) {
            $activity['description'] = trim(($activity['user_name'] ?? 'Someone') . ' ' . str_replace('_', ' ', $activity['action']));
            $activity['time_ago'] = timeAgo($activity['created_at']);
        }
        unset($activity);

        $data = [
            'user'                => $user,
            'total_projects'      => (int) $totalProjects,
            'active_projects'     => (int) $activeProjects,
            'total_contractors'   => (int) $totalContractors,
            'total_invoice_amount' => (float) $totalInvoiceAmount,
            'org_currency'        => $user['org_currency'] ?? DEFAULT_CURRENCY,
            'recent_projects'     => $recentProjects,
            'pending_invoices'    => $pendingInvoices,
            'upcoming_milestones' => $upcomingMilestones,
            'recent_activity'     => $recentActivity,
        ];

        $this->render('dashboard/org_dashboard', array_merge(['pageTitle' => 'Dashboard'], $data));
    }

    public function contractorDashboard() {
        $this->requireAuth();
        $user = Auth::user();
        $contractorId = $this->dbQueryOne("SELECT contractor_id FROM contractor_users WHERE user_id = ?", [Auth::id()])['contractor_id'] ?? 0;

        $assignedProjects = $this->dbQuery(
            "SELECT p.*, pc.status as assignment_status,
                    COALESCE((SELECT ROUND(SUM(status = 'completed') / COUNT(*) * 100) FROM project_milestones WHERE project_id = p.id), 0) as progress
             FROM projects p JOIN project_contractors pc ON p.id = pc.project_id
             WHERE pc.contractor_id = ? AND pc.status = 'accepted'",
            [$contractorId]
        );
        $pendingInvitations = $this->dbQuery(
            "SELECT pc.id, p.id as project_id, p.name as project_name, o.name as org_name
             FROM project_contractors pc
             INNER JOIN projects p ON pc.project_id = p.id
             INNER JOIN organizations o ON p.org_id = o.id
             WHERE pc.contractor_id = ? AND pc.status = 'pending'",
            [$contractorId]
        );
        $pendingInvoices  = $this->dbQuery("SELECT * FROM invoices WHERE contractor_id = ? AND status = 'submitted'", [$contractorId]);
        $reportsSubmitted = $this->dbQueryOne("SELECT COUNT(*) as cnt FROM project_reports WHERE contractor_id = ?", [$contractorId])['cnt'] ?? 0;
        $reportsToday     = $this->dbQueryOne("SELECT COUNT(DISTINCT project_id) as cnt FROM project_reports WHERE contractor_id = ? AND report_date = CURDATE()", [$contractorId])['cnt'] ?? 0;

        $recentReports = $this->dbQuery(
            "SELECT r.*, p.name as project_name FROM project_reports r
             INNER JOIN projects p ON r.project_id = p.id
             WHERE r.contractor_id = ? ORDER BY r.report_date DESC LIMIT 5",
            [$contractorId]
        );

        $invoiceTracker = $this->dbQuery("SELECT * FROM invoices WHERE contractor_id = ? ORDER BY created_at DESC LIMIT 5", [$contractorId]);
        $statusColors = ['paid' => 'success', 'approved' => 'info', 'rejected' => 'danger', 'under_review' => 'warning', 'submitted' => 'warning', 'draft' => 'secondary'];
        foreach ($invoiceTracker as &$inv) {
            $inv['status_color'] = $statusColors[$inv['status']] ?? 'secondary';
        }
        unset($inv);

        $data = [
            'user'                => $user,
            'assigned_projects'   => count($assignedProjects),
            'reports_submitted'   => (int) $reportsSubmitted,
            'reports_due_today'   => max(0, count($assignedProjects) - $reportsToday),
            'pending_invoices'    => count($pendingInvoices),
            'pending_invitations' => $pendingInvitations,
            'active_projects'     => $assignedProjects,
            'recent_reports'      => $recentReports,
            'invoice_tracker'     => $invoiceTracker,
        ];

        $this->render('dashboard/contractor_dashboard', array_merge(['pageTitle' => 'Contractor Portal'], $data));
    }

    public function superAdminDashboard() {
        $this->requireSuperAdmin();

        $data = [
            'total_orgs'     => (int) ($this->dbQueryOne("SELECT COUNT(*) as cnt FROM organizations")['cnt'] ?? 0),
            'total_users'    => (int) ($this->dbQueryOne("SELECT COUNT(*) as cnt FROM users")['cnt'] ?? 0),
            'total_projects' => (int) ($this->dbQueryOne("SELECT COUNT(*) as cnt FROM projects")['cnt'] ?? 0),
            'revenue_fees'   => (float) ($this->dbQueryOne("SELECT COALESCE(SUM(charge_amount),0) as total FROM subscription_charges WHERE status = 'paid'")['total'] ?? 0),
            'recent_orgs'    => $this->dbQuery("SELECT o.*, p.name as plan_name FROM organizations o LEFT JOIN plans p ON o.plan_id = p.id ORDER BY o.created_at DESC LIMIT 5"),
            'pending_charges' => $this->dbQuery("SELECT sc.*, o.name as org_name FROM subscription_charges sc JOIN organizations o ON sc.org_id = o.id WHERE sc.status = 'pending' ORDER BY sc.created_at DESC LIMIT 5"),
            'system_health'  => 'Healthy',
        ];

        $this->render('dashboard/super_admin_dashboard', array_merge(['pageTitle' => 'Platform Administration'], $data));
    }

    public function apiStats() {
        $this->requireAuth();
        $this->json([
            'projects_by_status' => [
                'planning'  => 2,
                'active'    => 5,
                'completed' => 10,
            ],
            'monthly_project_value' => [
                'Jan' => 10000, 'Feb' => 12000, 'Mar' => 15000,
                'Apr' => 11000, 'May' => 20000, 'Jun' => 18000,
            ],
        ]);
    }
}
