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

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

$message = '';
$message_type = '';
$success_count = 0;

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $client_ids = $_POST['client_ids'] ?? [];
    $user_id = $_POST['user_id'];
    $smm_user_id = $_POST['smm_user_id'];
    $schedule_type = $_POST['schedule_type'];
    $assign_day = '';

    if (empty($client_ids)) {
        $message = "Error: Please select at least one client.";
        $message_type = 'error';
    } else {
        // ===== FIX START: Check for existing schedules before creating new ones =====
        $placeholders = implode(',', array_fill(0, count($client_ids), '?'));
        $types = str_repeat('i', count($client_ids));
        
        $check_sql = "SELECT c.name FROM task_schedules ts JOIN clients c ON ts.client_id = c.id WHERE ts.client_id IN ($placeholders) AND ts.is_active = TRUE";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param($types, ...$client_ids);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        $existing_clients = [];
        while ($row = $result->fetch_assoc()) {
            $existing_clients[] = $row['name'];
        }
        $check_stmt->close();

        if (!empty($existing_clients)) {
            $message = "Schedule already exists for: " . implode(', ', $existing_clients);
            $message_type = 'error';
        } else {
            // ===== FIX END =====
            if ($schedule_type == 'Weekly') {
                $assign_day = isset($_POST['week_days']) ? implode(',', $_POST['week_days']) : '';
                if (empty($assign_day)) {
                     $message = "Error: Please select at least one day for a weekly schedule.";
                     $message_type = 'error';
                }
            } elseif ($schedule_type == 'Alternate') {
                $assign_day = $_POST['alternate_group'] ?? '';
            }

            if (empty($message)) {
                $conn->begin_transaction();
                try {
                    $stmt = $conn->prepare("INSERT INTO task_schedules (client_id, user_id, smm_user_id, schedule_type, assign_day) VALUES (?, ?, ?, ?, ?)");
                    
                    foreach ($client_ids as $client_id) {
                        $stmt->bind_param("iisss", $client_id, $user_id, $smm_user_id, $schedule_type, $assign_day);
                        $stmt->execute();
                        $success_count++;
                    }
                    
                    $conn->commit();
                    $_SESSION['message'] = "Success! {$success_count} new schedules were created.";
                    $_SESSION['message_type'] = 'success';
                    header("Location: schedules.php");
                    exit();

                } catch (mysqli_sql_exception $exception) {
                    $conn->rollback();
                    $message = "An error occurred: " . $exception->getMessage();
                    $message_type = 'error';
                }
            }
        }
    }
}

// --- DATA FETCHING for dropdowns ---
$all_clients_result = $conn->query("SELECT id, name FROM clients WHERE is_active = TRUE ORDER BY name ASC");
$all_clients = $all_clients_result->fetch_all(MYSQLI_ASSOC);

$users_result = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
$all_users = $users_result->fetch_all(MYSQLI_ASSOC);

$reviewers_result = $conn->query("
    SELECT DISTINCT u.id, u.name FROM users u
    JOIN user_roles ur ON u.id = ur.user_id
    JOIN roles r ON ur.role_id = r.id
    WHERE r.name IN ('Manager', 'SMM')
    ORDER BY u.name ASC
");
$all_reviewers = $reviewers_result->fetch_all(MYSQLI_ASSOC);

$conn->close();

require_once 'header.php';
?>

<title>Create New Schedule - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Create New Regular Task Schedule</h2>

<main class="p-6 md:p-10">
    <div class="max-w-3xl mx-auto bg-white p-8 rounded-lg shadow-lg">
        <?php if (!empty($message)): ?>
            <div class="mb-6 p-4 rounded <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="manage-schedule.php" x-data="{ scheduleType: 'Alternate' }">
            <div class="space-y-6">
                <div>
                    <label for="client_ids" class="block text-sm font-medium text-gray-700">1. Select Client(s)</label>
                    <p class="text-xs text-gray-500 mb-2">Hold Ctrl (or Cmd on Mac) to select multiple clients.</p>
                    <select name="client_ids[]" id="client_ids" required multiple class="mt-1 block w-full border-gray-300 rounded-md shadow-sm h-40">
                        <?php foreach ($all_clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>"><?php echo htmlspecialchars($client['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="user_id" class="block text-sm font-medium text-gray-700">2. Assign Task To</label>
                        <select name="user_id" id="user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option value="">-- Select Employee --</option>
                            <?php foreach ($all_users as $user): ?>
                                <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="smm_user_id" class="block text-sm font-medium text-gray-700">3. Review By (SMM)</label>
                        <select name="smm_user_id" id="smm_user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option value="">-- Select SMM/Manager --</option>
                            <?php foreach ($all_reviewers as $user): ?>
                                <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">4. Choose Schedule Type</label>
                    <div class="mt-2 space-y-2">
                        <label class="flex items-center p-3 border rounded-lg" :class="{ 'bg-blue-50 border-blue-300': scheduleType === 'Daily' }">
                            <input type="radio" name="schedule_type" value="Daily" x-model="scheduleType" class="h-4 w-4 text-blue-600 border-gray-300">
                            <span class="ml-3 text-sm font-medium text-gray-800">Daily (Excluding Sunday)</span>
                        </label>
                        <label class="flex items-center p-3 border rounded-lg" :class="{ 'bg-blue-50 border-blue-300': scheduleType === 'Alternate' }">
                            <input type="radio" name="schedule_type" value="Alternate" x-model="scheduleType" class="h-4 w-4 text-blue-600 border-gray-300">
                            <span class="ml-3 text-sm font-medium text-gray-800">Alternate Days (Group Wise)</span>
                        </label>
                        <label class="flex items-center p-3 border rounded-lg" :class="{ 'bg-blue-50 border-blue-300': scheduleType === 'Weekly' }">
                            <input type="radio" name="schedule_type" value="Weekly" x-model="scheduleType" class="h-4 w-4 text-blue-600 border-gray-300">
                            <span class="ml-3 text-sm font-medium text-gray-800">Weekly (Custom Days)</span>
                        </label>
                    </div>
                </div>
                
                <div x-show="scheduleType === 'Alternate'" class="pt-4 border-t">
                     <label for="alternate_group" class="block text-sm font-medium text-gray-700">Select Client Group</label>
                     <p class="text-xs text-gray-500 mb-2">Group A tasks will be created on Mon, Wed, Fri. Group B on Tue, Thu, Sat.</p>
                     <select name="alternate_group" id="alternate_group" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                         <option value="GroupA">Group A (Mon, Wed, Fri)</option>
                         <option value="GroupB">Group B (Tue, Thu, Sat)</option>
                    </select>
                </div>

                <div x-show="scheduleType === 'Weekly'" class="pt-4 border-t">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Select Days of the Week</label>
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                        <?php $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; ?>
                        <?php foreach ($days as $day): ?>
                            <label class="inline-flex items-center"><input type="checkbox" name="week_days[]" value="<?php echo $day; ?>" class="rounded border-gray-300 text-blue-600 shadow-sm"><span class="ml-2 text-sm text-gray-600"><?php echo $day; ?></span></label>
                        <?php endforeach; ?>
                    </div>
                </div>

            </div>
            <div class="flex justify-end mt-8">
                <a href="schedules.php" class="px-4 py-2 border rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50">Cancel</a>
                <button type="submit" class="ml-3 inline-flex items-center px-4 py-2 bg-blue-600 border-transparent rounded-md font-semibold text-white hover:bg-blue-700">
                    Save Schedule(s)
                </button>
            </div>
        </form>
    </div>
</main>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>
