<?php
// create_report_tasks.php
require_once 'init.php';

// Suraksha jaanch: Sirf Admin ya Manager hi trigger kar sakein
if (!userHasRole(['Admin', 'Manager'])) {
    die(json_encode(['status' => 'error', 'message' => 'Unauthorized access.']));
}

echo "Starting 10-Day Report Task Generation (System Start Date: 2026-01-15)...\n";

// --- CONFIGURATION ---
$system_start_dt = new DateTime('2026-01-15');
$today_dt = new DateTime();
$today_str = date('Y-m-d');

// 1. 'Analyst' role ki ID fetch karein (roles table mein column 'name' hai)
$role_sql = "SELECT id FROM roles WHERE name = 'Analyst' LIMIT 1";
$role_query = $conn->query($role_sql);

if (!$role_query || $role_query->num_rows == 0) {
    die("ERROR: Role 'Analyst' not found in 'roles' table. Please ensure the role exists.");
}

$analytic_role = $role_query->fetch_assoc();
$analytic_role_id = $analytic_role['id'];

// 2. task_schedules aur user_roles se mapping uthayein
$mapping_sql = "SELECT ts.client_id, ts.smm_user_id, c.name as client_name, c.activation_date 
                FROM task_schedules ts
                JOIN clients c ON ts.client_id = c.id
                JOIN user_roles ur ON ts.smm_user_id = ur.user_id
                WHERE ur.role_id = $analytic_role_id 
                AND c.is_active = 1
                GROUP BY ts.client_id, ts.smm_user_id";

$mapping_res = $conn->query($mapping_sql);

if (!$mapping_res) {
    die("DATABASE ERROR: Mapping query failed - " . $conn->error);
}

$tasks_created = 0;

while ($row = $mapping_res->fetch_assoc()) {
    $client_id = $row['client_id'];
    $manager_id = $row['smm_user_id'];
    $client_name = $row['client_name'];
    $client_activation_dt = new DateTime($row['activation_date']);

    // LOGIC: 15 JAN 2026 Starting Point
    $effective_start_date = ($client_activation_dt < $system_start_dt) ? $system_start_dt : $client_activation_dt;

    // Check last report date
    $last_rep_query = $conn->query("SELECT MAX(report_date) as last_date FROM client_reports WHERE client_id = $client_id");
    $last_date_str = ($last_rep_query) ? $last_rep_query->fetch_assoc()['last_date'] : null;
    
    $base_date = (!empty($last_date_str)) ? new DateTime($last_date_str) : $effective_start_date;

    if ($base_date > $today_dt) continue;

    $days_diff = $today_dt->diff($base_date)->days;

    // 10 din ka cycle check
    if ($days_diff >= 10) {
        
        // DUPLICATE CHECK: Aaj ka task check karein (Title aur Type ke aadhar par)
        // Yahan 'Pending' ke bajaye ab hum 'Not Started' check karenge purane generated tasks ke liye
        $check_sql = "SELECT id FROM tasks WHERE client_id = ? AND work_type = 'Report' AND (status IN ('Not Started', 'Pending')) AND DATE(assigned_date) = ?";
        $check_stmt = $conn->prepare($check_sql);
        if ($check_stmt) {
            $check_stmt->bind_param("is", $client_id, $today_str);
            $check_stmt->execute();
            $is_duplicate = $check_stmt->get_result()->num_rows > 0;
            $check_stmt->close();

            if (!$is_duplicate) {
                $title = "Create 10-Day Report for " . $client_name;
                $desc = "Scheduled Report Task (Cycle starting from Jan 15 or Activation).";
                
                // STATUS CHANGE: Ab status 'Not Started' rakha hai takki pending_reports.php mein dikhe
                $ins_sql = "INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, description, task_type, work_type, priority, assigned_date, status) VALUES (?, ?, ?, ?, ?, 'Additional', 'Report', 'High', ?, 'Not Started')";
                
                $ins = $conn->prepare($ins_sql);
                if ($ins) {
                    $ins->bind_param("iiisss", $client_id, $manager_id, $manager_id, $title, $desc, $today_str);
                    if ($ins->execute()) {
                        echo "SUCCESS: Task created for $client_name (Status: Not Started)\n";
                        $tasks_created++;
                    }
                    $ins->close();
                }
            } else {
                echo "INFO: Task already exists for $client_name today. Skipping.\n";
            }
        }
    } else {
        $remaining = 10 - $days_diff;
        echo "INFO: $client_name report not due yet ($remaining days remaining).\n";
    }
}

echo "\nProcess Finished. Total tasks created: $tasks_created\n";
?>