<?php
// PHP Error reporting for debugging (comment out in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load PHPMailer classes from the PHPMailer-master/src directory
// We are using __DIR__ to make paths robust for Cron Jobs
require_once __DIR__ . '/PHPMailer-master/src/Exception.php';
require_once __DIR__ . '/PHPMailer-master/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer-master/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

// NOTE: We no longer rely on config.php for core configurations (DB, SMTP, Roles)
// but keep the require for recipient emails fallback logic.
require_once __DIR__ . '/config.php';

// ====================================================================
// 0. HARDCODED CONFIGURATION FOR REPORTING ONLY (DO NOT MODIFY CONFIG.PHP)
//    ALL CRITICAL CONFIGURATION IS DEFINED HERE.
// ====================================================================

// Database Credentials
define('DB_HOST', 'localhost');
define('DB_USER', 'cybsoul_loyality');
define('DB_PASS', 'Digital@1270');
define('DB_NAME', 'cybsoul_taskapp');

// Email (SMTP) Credentials
define('SMTP_HOST', 'digifytech.in');
define('SMTP_USERNAME', 'info@digifytech.in');
define('SMTP_PASSWORD', 'Digify@123');
define('SMTP_PORT', 587);
define('SMTP_SENDER_NAME', 'Auto Report System');

// --- ROLE MAPPING (HARDCODED) ---
// User-provided Role IDs: SMM=5, Graphic Designer=3, Video Editor=4
const ROLE_SMM = 5;
const ROLE_GD = 3;
const ROLE_VE = 4;

$roles_to_report = [
    'SMM'               => ROLE_SMM,
    'Production Team'   => [ROLE_GD, ROLE_VE], // Combined for reporting
];

// --- RECIPIENT FALLBACK ---
// If config.php failed to define $recipient_emails, use these defaults.
if (!isset($recipient_emails) || empty($recipient_emails)) {
    $recipient_emails = [
        'republicmedia.biz@gmail.com'
    ];
}

// ====================================================================
// 1. DATABASE CONNECTION
// ====================================================================

function get_db_connection() {
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        // Log the error but continue execution for testing purposes
        error_log("Database Connection Error: " . $e->getMessage());
        return null;
    }
}

// ====================================================================
// 2. DATA FETCHING LOGIC
// ====================================================================

/**
 * Fetches data for a single user (Production Team) or an aggregated report (SMM).
 * @param PDO $pdo The PDO connection object.
 * @param int|array $role_id The role ID or array of IDs to filter by.
 * @param string $role_name The name of the role/team.
 * @return array The processed report data.
 */
function get_report_data_for_role(PDO $pdo, $role_id, $role_name) {
    // ----------------------------------------------------------------------
    // 2.1 PRODUCTION TEAM / SMM USER FETCH (DISTINCT USERS)
    // ----------------------------------------------------------------------
    
    // Convert role_id to string for SQL IN clause
    $role_filter = is_array($role_id) ? implode(',', $role_id) : $role_id;
    
    // Fetch distinct users based on the role filter
    $stmt_users = $pdo->prepare("
        SELECT DISTINCT u.id, u.name 
        FROM users u
        INNER JOIN user_roles ur ON u.id = ur.user_id
        WHERE ur.role_id IN ({$role_filter})
    ");
    $stmt_users->execute();
    $users_data = $stmt_users->fetchAll(PDO::FETCH_ASSOC);

    $report_data = [];

    // ----------------------------------------------------------------------
    // 2.2 MAIN TASK DATA LOOP
    // ----------------------------------------------------------------------

    foreach ($users_data as $user) {
        $user_id = $user['id'];

        // --- PRODUCTION TEAM LOGIC (GD/VE) ---
        if ($role_name === 'Production Team') {
            
            // 1. TOTAL ASSIGNED (Today's assigned tasks - ALL types)
            $stmt_assigned = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE assigned_user_id = :user_id 
                AND DATE(assigned_date) = CURDATE()
            ");
            $stmt_assigned->execute([':user_id' => $user_id]);
            $assigned_today = $stmt_assigned->fetch(PDO::FETCH_ASSOC)['count'];
            
            // 2. DONE (Completed OR In Review - Today's time till NOW)
            // Done includes 'Completed' AND 'In Review' statuses, completed today up to now.
            $stmt_done = $pdo->prepare("
                SELECT 
                    COUNT(CASE WHEN (status = 'Completed' OR status = 'In Review') AND DATE(completed_at) = CURDATE() AND completed_at <= NOW() THEN 1 END) AS count_done_today,
                    COUNT(CASE WHEN task_type = 'Additional' AND DATE(assigned_date) = CURDATE() THEN 1 END) AS count_additional
                FROM tasks
                WHERE assigned_user_id = :user_id
            ");
            $stmt_done->execute([':user_id' => $user_id]);
            $done_metrics = $stmt_done->fetch(PDO::FETCH_ASSOC);

            // 3. PENDING (Not Started OR In Process - Overall)
            $stmt_pending = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE assigned_user_id = :user_id 
                AND (status = 'Not Started' OR status = 'In Process')
            ");
            $stmt_pending->execute([':user_id' => $user_id]);
            $pending_overall = $stmt_pending->fetch(PDO::FETCH_ASSOC)['count'];
            
            // 4. OVERDUE (Overall - Assigned before today, not completed, rejected, or skipped)
            $stmt_overdue = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE assigned_user_id = :user_id 
                AND DATE(assigned_date) < CURDATE() 
                AND status != 'Completed' AND status != 'Rejected' AND status != 'Skipped'
            ");
            $stmt_overdue->execute([':user_id' => $user_id]);
            $overdue_overall = $stmt_overdue->fetch(PDO::FETCH_ASSOC)['count'];

            $report_data[] = [
                'user_name'         => $user['name'],
                'role_name'         => $role_name,
                'total_assigned'    => $assigned_today,
                'done_task'         => $done_metrics['count_done_today'],
                'pending_task'      => $pending_overall,
                'overdue_task'      => $overdue_overall,
                'count_additional'  => $done_metrics['count_additional'], // New Metric
            ];


        // --- SMM LOGIC (Reviewer/Posting) ---
        } elseif ($role_name === 'SMM') {
            
            // 1. TOTAL ASSIGNED (SMM Assigned Today + SMM Created Today)
            // Assigned Count (where assigned_user_id is SMM, ALL task types)
            $stmt_assigned_direct = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE assigned_user_id = :user_id AND DATE(assigned_date) = CURDATE()
            ");
            $stmt_assigned_direct->execute([':user_id' => $user_id]);
            $assigned_count = $stmt_assigned_direct->fetch(PDO::FETCH_ASSOC)['count'];

            // Created Count (where created_by is SMM, ALL task types) - serves as reviewer/creator total
            $stmt_created = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE created_by = :user_id AND DATE(created_at) = CURDATE()
            ");
            $stmt_created->execute([':user_id' => $user_id]);
            $created_count = $stmt_created->fetch(PDO::FETCH_ASSOC)['count'];

            $total_assigned_combined = ($assigned_count ?? 0) + ($created_count ?? 0);
            
            // 2. DONE (Completed tasks - Today's time till NOW)
            // SMM Done tasks are only 'Completed' status (approved/posted)
            $stmt_done = $pdo->prepare("
                SELECT COUNT(CASE WHEN status = 'Completed' AND DATE(completed_at) = CURDATE() AND completed_at <= NOW() THEN 1 END) AS count_done_today
                FROM tasks
                WHERE assigned_user_id = :user_id
            ");
            $stmt_done->execute([':user_id' => $user_id]);
            $done_metrics = $stmt_done->fetch(PDO::FETCH_ASSOC);

            // 3. PENDING (Overall pending tasks assigned to SMM)
            // SMM's direct pending tasks (Not Started/In Process)
            $stmt_pending_direct = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE assigned_user_id = :user_id 
                AND (status = 'Not Started' OR status = 'In Process')
            ");
            $stmt_pending_direct->execute([':user_id' => $user_id]);
            $pending_overall_direct = $stmt_pending_direct->fetch(PDO::FETCH_ASSOC)['count'];


            // 4. OVERDUE (Overall)
            $stmt_overdue = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE assigned_user_id = :user_id 
                AND due_date < CURDATE() 
                AND status != 'Completed' AND status != 'Rejected' AND status != 'Skipped'
            ");
            $stmt_overdue->execute([':user_id' => $user_id]);
            $overdue_overall = $stmt_overdue->fetch(PDO::FETCH_ASSOC)['count'];

            // 5. PENDING APPROVAL (Overall - Where SMM is the Creator/Reviewer)
            $stmt_pending_approval = $pdo->prepare("
                SELECT COUNT(id) AS count
                FROM tasks
                WHERE created_by = :user_id 
                AND status = 'In Review'
            ");
            $stmt_pending_approval->execute([':user_id' => $user_id]);
            $pending_approval_count = $stmt_pending_approval->fetch(PDO::FETCH_ASSOC)['count'];

            $report_data[] = [
                'user_name'             => $user['name'],
                'role_name'             => $role_name,
                'total_assigned'        => $total_assigned_combined,
                'done_task'             => $done_metrics['count_done_today'],
                'pending_task'          => $pending_overall_direct,
                'overdue_task'          => $overdue_overall,
                'smm_pending_approval'  => $pending_approval_count, 
            ];
        }
    }

    return $report_data;
}


// ====================================================================
// 3. HTML GENERATION
// ====================================================================

/**
 * Generates the full HTML email body with responsive design.
 * @param array $all_report_data The combined report data.
 * @return string The HTML content.
 */
function generate_report_html(array $all_report_data): string {
    $report_time = date('F j, Y, h:i A');

    // CSS for responsive design and card layout on mobile
    $css = "
        <style>
            /* Global Styles */
            body, html { margin: 0; padding: 0; font-family: 'Inter', sans-serif; background-color: #f4f7f6; }
            .container { max-width: 700px; margin: 0 auto; padding: 20px; background-color: #ffffff; border-radius: 8px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); }
            .header { background-color: #007bff; color: white; padding: 20px; border-radius: 8px 8px 0 0; text-align: center; }
            .report-title { font-size: 24px; font-weight: 700; margin: 0; }
            .report-time { font-size: 14px; opacity: 0.8; margin-top: 5px; }

            /* Table Styles (Desktop View) */
            .report-table { width: 100%; border-collapse: collapse; margin-top: 20px; table-layout: fixed; }
            .report-table th, .report-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #e0e0e0; font-size: 14px; }
            .report-table th { background-color: #f4f7f6; color: #444; font-weight: 600; text-transform: uppercase; }
            .report-table tr:hover { background-color: #f9f9f9; }
            .metric-value { font-weight: 700; color: #007bff; }
            .overdue { color: #dc3545; font-weight: 700; }
            .pending { color: #ffc107; font-weight: 700; }

            /* Mobile Card View (Hidden on Desktop) */
            .mobile-card-view { display: none; margin-top: 20px; }
            .user-card { background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 15px; padding: 15px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); }
            .card-header { font-size: 18px; font-weight: 700; margin-bottom: 10px; color: #333; border-bottom: 2px solid #007bff; padding-bottom: 5px; }
            .metric-item { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed #eee; font-size: 14px; }
            .metric-label { color: #666; font-weight: 500; }

            /* Responsive CSS */
            @media screen and (max-width: 600px) {
                /* Hide Table, Show Cards */
                .desktop-table-view { display: none !important; }
                .mobile-card-view { display: block !important; }
                .container { padding: 10px; }
                .report-title { font-size: 20px; }
                .header { border-radius: 0; }
            }
        </style>
    ";

    $html = "<!DOCTYPE html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'>{$css}</head><body><div class='container'><div class='header'><h1 class='report-title'>Daily Task Performance Report</h1><p class='report-time'>Generated on: {$report_time}</p></div>";

    $current_role = '';
    $html .= "<div class='desktop-table-view'>";

    foreach ($all_report_data as $row) {
        if ($row['role_name'] !== $current_role) {
            // Close previous table if exists
            if ($current_role !== '') {
                $html .= "</tbody></table>";
            }
            // Start new table group
            $current_role = $row['role_name'];
            $html .= "<h3 style='margin-top: 30px; font-size: 20px; color: #333;'>Team: {$current_role}</h3>";
            $html .= "<table class='report-table'><thead><tr>";

            // Define column headers based on role
            $headers = ['User Name', 'Assigned (Today)', 'Done (Today)', 'Pending (Overall)', 'Overdue (Overall)'];
            if ($row['role_name'] === 'Production Team') {
                $headers = array_merge($headers, ['Additional Tasks (Today)']);
            } elseif ($row['role_name'] === 'SMM') {
                // SMM now uses 'Pending Approval (Overall)'
                $headers = array_merge($headers, ['Pending Approval (Overall)']);
            }
            foreach ($headers as $header) {
                $html .= "<th>{$header}</th>";
            }
            $html .= "</tr></thead><tbody>";
        }

        // Add table row
        $html .= "<tr>";
        $html .= "<td>" . htmlspecialchars($row['user_name']) . "</td>";
        $html .= "<td><span class='metric-value'>" . $row['total_assigned'] . "</span></td>";
        $html .= "<td><span class='metric-value'>" . $row['done_task'] . "</span></td>";
        $html .= "<td><span class='pending'>" . $row['pending_task'] . "</span></td>";
        $html .= "<td><span class='overdue'>" . $row['overdue_task'] . "</span></td>";

        // Role-specific columns
        if ($row['role_name'] === 'Production Team') {
            $html .= "<td>" . $row['count_additional'] . "</td>";
        } elseif ($row['role_name'] === 'SMM') {
            $html .= "<td><span class='pending'>" . $row['smm_pending_approval'] . "</span></td>";
        }
        $html .= "</tr>";
    }

    // Close last table
    if ($current_role !== '') {
        $html .= "</tbody></table>";
    }
    $html .= "</div>"; // End desktop-table-view

    // --- Mobile Card View ---
    $current_role_mobile = '';
    $html .= "<div class='mobile-card-view'>";

    foreach ($all_report_data as $row) {
        // Prepare data labels for mobile view
        $metrics = [
            'Assigned (Today)'          => $row['total_assigned'],
            'Done (Today)'              => $row['done_task'],
            'Pending (Overall)'         => $row['pending_task'],
            'Overdue (Overall)'         => $row['overdue_task'],
        ];
        
        if ($row['role_name'] === 'Production Team') {
            $metrics['Additional Tasks (Today)'] = $row['count_additional'];
        } elseif ($row['role_name'] === 'SMM') {
             $metrics['Pending Approval (Overall)'] = $row['smm_pending_approval'];
        }

        // Display team header if role changes
        if ($row['role_name'] !== $current_role_mobile) {
            $current_role_mobile = $row['role_name'];
            $html .= "<h3 style='margin-top: 20px; font-size: 18px; color: #333; border-bottom: 1px solid #ccc; padding-bottom: 5px;'>Team: {$current_role_mobile}</h3>";
        }

        // Card start
        $html .= "<div class='user-card'>";
        $html .= "<div class='card-header'>" . htmlspecialchars($row['user_name']) . "</div>";

        // Display metrics in card
        foreach ($metrics as $label => $value) {
            $style = '';
            if (strpos($label, 'Done') !== false || strpos($label, 'Assigned') !== false) {
                $style = 'color: #007bff; font-weight: 700;';
            } elseif (strpos($label, 'Pending') !== false || strpos($label, 'Approval') !== false) {
                 $style = 'color: #ffc107; font-weight: 700;';
            } elseif (strpos($label, 'Overdue') !== false) {
                $style = 'color: #dc3545; font-weight: 700;';
            }

            $html .= "<div class='metric-item'>";
            $html .= "<span class='metric-label'>{$label}:</span>";
            $html .= "<span style='{$style}'>{$value}</span>";
            $html .= "</div>";
        }
        
        $html .= "</div>"; // Card end
    }

    $html .= "</div>"; // End mobile-card-view
    $html .= "</div></body></html>";
    return $html;
}


// ====================================================================
// 4. EMAIL SENDING LOGIC
// ====================================================================

/**
 * Sends the generated HTML report via PHPMailer.
 * @param string $subject The email subject.
 * @param string $body The HTML body content.
 * @param array $recipients Array of email addresses.
 * @return bool True on success, false on failure.
 */
function send_report_email(string $subject, string $body, array $recipients): bool {
    // Safety check for recipients
    if (empty($recipients)) {
        error_log("PHPMailer Error: No recipient email address provided.");
        return false;
    }

    $mail = new PHPMailer(true); // Enable exceptions
    try {
        // Server settings
        $mail->SMTPDebug = SMTP::DEBUG_OFF; // Enable verbose debug output for testing if needed (use DEBUG_SERVER)
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Use ENCRYPTION_SMTPS for port 465
        $mail->Port       = SMTP_PORT;

        // Recipients
        $mail->setFrom(SMTP_USERNAME, SMTP_SENDER_NAME);
        foreach ($recipients as $email) {
            $mail->addAddress($email);
        }

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags($body); // For non-HTML mail clients

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log("PHPMailer Error: {$mail->ErrorInfo}");
        echo "PHPMailer Error: {$mail->ErrorInfo} Report sending failed.";
        return false;
    }
}


// ====================================================================
// 5. MAIN EXECUTION
// ====================================================================

function main(array $roles_to_report, array $recipient_emails) {
    $pdo = get_db_connection();
    if (!$pdo) {
        echo "Database connection is not available. Report generation aborted.";
        return;
    }

    $all_report_data = [];

    // Loop through roles to fetch data
    foreach ($roles_to_report as $role_name => $role_id) {
        $data = get_report_data_for_role($pdo, $role_id, $role_name);
        $all_report_data = array_merge($all_report_data, $data);
    }
    
    // Safety check: ensure only unique users are reported (useful for combined roles)
    $unique_users_data = [];
    $seen_users = [];

    foreach ($all_report_data as $data) {
        $key = $data['user_name'] . $data['role_name'];
        if (!in_array($data['user_name'], $seen_users)) {
            $unique_users_data[] = $data;
            $seen_users[] = $data['user_name'];
        }
    }


    if (empty($unique_users_data)) {
        echo "No user data found. Report sending aborted.";
        return;
    }

    // Generate HTML
    $html_report = generate_report_html($unique_users_data);

    // Send Email
    $subject = "Daily Performance Report - " . date('Y-m-d H:i:s');
    
    if (send_report_email($subject, $html_report, $recipient_emails)) {
        echo "Report Sent Successfully.";
    } else {
        echo "Report sending failed. Check server error log for details.";
    }
}

// Execute the main function
main($roles_to_report, $recipient_emails);

// End of file marker
?>
