<?php
// init.php ko shaamil karein
require_once 'init.php';

// Suraksha jaanch
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
$user_id = $_SESSION['user_id'];

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['client_id'])) {
    $client_id = (int)$_POST['client_id'];
    
    // Agle 7 dino mein is client ke liye agla schedule dhoondhein
    $next_task_date = null;
    $schedule_info = null;

    for ($i = 1; $i <= 7; $i++) {
        $check_date = date('Y-m-d', strtotime("+$i day"));
        $day_name = date('l', strtotime($check_date));

        $sql = "SELECT * FROM task_schedules WHERE client_id = ? AND user_id = ? AND is_active = TRUE";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $client_id, $user_id);
        $stmt->execute();
        $schedules = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        foreach($schedules as $schedule) {
            // Check karein ki is din ke liye task pehle se to nahi bana hai
            $check_existing_sql = "SELECT id FROM tasks WHERE client_id = ? AND assigned_user_id = ? AND assigned_date = ? AND task_type = 'Regular'";
            $stmt_check = $conn->prepare($check_existing_sql);
            $stmt_check->bind_param("iis", $client_id, $user_id, $check_date);
            $stmt_check->execute();
            if ($stmt_check->get_result()->num_rows > 0) {
                $stmt_check->close();
                continue; // Task pehle se hai
            }
            $stmt_check->close();

            // Schedule type ke anusaar task banayein
            $is_scheduled_today = false;
            if ($schedule['schedule_type'] == 'Daily') {
                $is_scheduled_today = true;
            } elseif ($schedule['schedule_type'] == 'Weekly' && in_array($day_name, explode(',', $schedule['assign_day']))) {
                $is_scheduled_today = true;
            } elseif ($schedule['schedule_type'] == 'Alternate') {
                $group_to_run = '';
                if (in_array($day_name, ['Monday', 'Wednesday', 'Friday'])) { $group_to_run = 'GroupA'; }
                elseif (in_array($day_name, ['Tuesday', 'Thursday', 'Saturday'])) { $group_to_run = 'GroupB'; }
                if ($schedule['assign_day'] == $group_to_run) {
                    $is_scheduled_today = true;
                }
            }
            
            if($is_scheduled_today) {
                $next_task_date = $check_date;
                $schedule_info = $schedule;
                break 2; // Dono loops se bahar aa jaayein
            }
        }
    }
    
    // Agar agla schedule mil gaya hai, to task banayein
    if ($next_task_date && $schedule_info) {
        // Client ka naam database se prapt karein
        $client_stmt = $conn->prepare("SELECT name FROM clients WHERE id = ?");
        $client_stmt->bind_param("i", $client_id);
        $client_stmt->execute();
        $client_name = $client_stmt->get_result()->fetch_assoc()['name'];
        $client_stmt->close();
        
        $task_title = "Regular Task for " . $client_name;
        $work_type = "Post"; // Default work type
        $smm_user_id = $schedule_info['smm_user_id'];

        $insert_sql = "INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, task_type, work_type, assigned_date) VALUES (?, ?, ?, ?, 'Regular', ?, ?)";
        $stmt_insert = $conn->prepare($insert_sql);
        $stmt_insert->bind_param("iissss", $client_id, $user_id, $smm_user_id, $task_title, $work_type, $next_task_date);
        
        if ($stmt_insert->execute()) {
            $_SESSION['message'] = "Advance task for " . date("d M, Y", strtotime($next_task_date)) . " has been assigned to you.";
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = "Error: Could not create the advance task.";
            $_SESSION['message_type'] = 'error';
        }
        $stmt_insert->close();
    } else {
        $_SESSION['message'] = "No upcoming regular task schedule found for this client in the next 7 days.";
        $_SESSION['message_type'] = 'error';
    }
}

$conn->close();
header("Location: my_tasks.php");
exit();
?>