<?php
// init.php ko shaamil karein, jo sab kuch setup karega
require_once 'init.php';

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: schedules.php");
    exit();
}
$schedule_id = (int)$_GET['id'];

// Session se message prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

// --- FORM SUBMISSION LOGIC (PRG Pattern ke saath) ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // DELETE SCHEDULE LOGIC
    if (isset($_POST['delete_schedule'])) {
        if (userHasRole(['Admin'])) {
            $admin_password = $_POST['admin_password'];
            $admin_id = $_SESSION['user_id'];
            
            $stmt = $conn->prepare("SELECT password_hash FROM users WHERE id = ?");
            $stmt->bind_param("i", $admin_id);
            $stmt->execute();
            $admin_user = $stmt->get_result()->fetch_assoc();

            if ($admin_user && password_verify($admin_password, $admin_user['password_hash'])) {
                $delete_stmt = $conn->prepare("DELETE FROM task_schedules WHERE id = ?");
                $delete_stmt->bind_param("i", $schedule_id);
                if ($delete_stmt->execute()) {
                    $_SESSION['message'] = "Schedule deleted successfully!";
                    $_SESSION['message_type'] = 'success';
                    header("Location: schedules.php");
                    exit();
                }
            } else {
                $_SESSION['message'] = "Incorrect admin password. Deletion failed.";
                $_SESSION['message_type'] = 'error';
            }
        }
    }
    // UPDATE SCHEDULE LOGIC
    elseif (isset($_POST['update_schedule'])) {
        $client_id = $_POST['client_id'];
        $user_id = $_POST['user_id'];
        $smm_user_id = $_POST['smm_user_id'];
        $schedule_type = $_POST['schedule_type'];
        $assign_day = '';

        if ($schedule_type == 'Weekly') {
            $assign_day = isset($_POST['week_days']) ? implode(',', $_POST['week_days']) : '';
        } elseif ($schedule_type == 'Alternate') {
            $assign_day = $_POST['alternate_group'] ?? '';
        }

        $stmt = $conn->prepare("UPDATE task_schedules SET client_id = ?, user_id = ?, smm_user_id = ?, schedule_type = ?, assign_day = ? WHERE id = ?");
        $stmt->bind_param("iisssi", $client_id, $user_id, $smm_user_id, $schedule_type, $assign_day, $schedule_id);
        if ($stmt->execute()) {
            $_SESSION['message'] = "Schedule updated successfully!";
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = "Error updating schedule: " . $stmt->error;
            $_SESSION['message_type'] = 'error';
        }
        $stmt->close();
    }
    
    // Action ke baad page ko redirect karein
    header("Location: edit-schedule.php?id=" . $schedule_id);
    exit();
}

// --- DATA FETCHING ---
$stmt = $conn->prepare("SELECT * FROM task_schedules WHERE id = ?");
$stmt->bind_param("i", $schedule_id);
$stmt->execute();
$schedule = $stmt->get_result()->fetch_assoc();
if (!$schedule) {
    header("Location: schedules.php");
    exit();
}
$stmt->close();

$all_clients = $conn->query("SELECT id, name FROM clients WHERE is_active = TRUE ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);
$all_users = $conn->query("SELECT id, name FROM users ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);
$conn->close();

// Ab yahan par header.php ko include karein
require_once 'header.php';
?>

<title>Edit Schedule - Digify OS</title>

<div class="flex-1" x-data="{ isDeleteModalOpen: false }">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">Edit Regular Task Schedule</h2>
    </header>

<main class="p-6 md:p-10">
    <div class="max-w-3xl mx-auto">
        <div class="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="edit-schedule.php?id=<?php echo $schedule_id; ?>" x-data="{ scheduleType: '<?php echo htmlspecialchars($schedule['schedule_type']); ?>' }">
                <div class="space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Client</label>
                        <select name="client_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <?php foreach ($all_clients as $client): ?>
                                <option value="<?php echo $client['id']; ?>" <?php if($schedule['client_id'] == $client['id']) echo 'selected'; ?>><?php echo htmlspecialchars($client['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="grid grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium">Assign To</label>
                            <select name="user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                                <?php foreach ($all_users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" <?php if($schedule['user_id'] == $user['id']) echo 'selected'; ?>><?php echo htmlspecialchars($user['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Review By</label>
                            <select name="smm_user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                                <?php foreach ($all_users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" <?php if($schedule['smm_user_id'] == $user['id']) echo 'selected'; ?>><?php echo htmlspecialchars($user['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Schedule Type</label>
                        <select name="schedule_type" x-model="scheduleType" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option value="Weekly" <?php if($schedule['schedule_type'] == 'Weekly') echo 'selected'; ?>>Weekly (Custom Days)</option>
                            <option value="Alternate" <?php if($schedule['schedule_type'] == 'Alternate') echo 'selected'; ?>>Alternate Days (Group Wise)</option>
                            <option value="Daily" <?php if($schedule['schedule_type'] == 'Daily') echo 'selected'; ?>>Daily (Every Day)</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</label><div class="grid grid-cols-2 sm:grid-cols-4 gap-4"><?php $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; $selected_days = explode(',', $schedule['assign_day']); ?><?php foreach ($days as $day): ?><label class="inline-flex items-center"><input type="checkbox" name="week_days[]" value="<?php echo $day; ?>" <?php if(in_array($day, $selected_days)) echo 'checked'; ?> class="rounded border-gray-300"><span class="ml-2 text-sm"><?php echo $day; ?></span></label><?php endforeach; ?></div></div>
                    <div x-show="scheduleType === 'Alternate'" class="pt-4 border-t"><label class="block text-sm font-medium">Select Group</label><select name="alternate_group" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"><option value="GroupA" <?php if($schedule['assign_day'] == 'GroupA') echo 'selected'; ?>>Group A (Mon, Wed, Fri)</option><option value="GroupB" <?php if($schedule['assign_day'] == 'GroupB') echo 'selected'; ?>>Group B (Tue, Thu, Sat)</option></select></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 hover:bg-gray-50">Cancel</a>
                    <button type="submit" name="update_schedule" class="ml-3 px-4 py-2 bg-blue-600 text-white rounded-md font-semibold hover:bg-blue-700">Update Schedule</button>
                </div>
            </form>
        </div>

        <?php if (userHasRole(['Admin'])): ?>
        <div class="mt-10 border-t-2 border-red-200 pt-6">
            <div class="flex justify-between items-center">
                <div><h3 class="text-lg font-semibold text-gray-700">Danger Zone</h3><p class="text-sm text-gray-600">This action cannot be undone.</p></div>
                <button @click="isDeleteModalOpen = true" class="bg-transparent border border-red-600 text-red-600 hover:bg-red-600 hover:text-white font-bold py-2 px-4 rounded-lg text-sm">Delete Schedule</button>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<div x-show="isDeleteModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center z-50" @keydown.escape.window="isDeleteModalOpen = false">
    <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-lg" @click.away="isDeleteModalOpen = false">
        <h3 class="text-xl font-semibold text-red-800 mb-4">Confirm Deletion</h3>
        <p class="text-gray-600 mb-6">Are you sure you want to delete this schedule? This will stop future automatic tasks for this client.</p>
        <form method="POST" action="edit-schedule.php?id=<?php echo $schedule_id; ?>">
            <div class="mb-4">
                <label for="admin_password" class="block text-sm font-medium text-gray-700">Enter your admin password to confirm</label>
                <input type="password" name="admin_password" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
            </div>
            <div class="flex justify-end mt-8">
                <button type="button" @click="isDeleteModalOpen = false" class="px-4 py-2 border rounded-md">Cancel</button>
                <button type="submit" name="delete_schedule" class="ml-3 px-4 py-2 bg-red-600 text-white rounded-md font-semibold hover:bg-red-700">I understand, delete this schedule</button>
            </div>
        </form>
    </div>
</div>

</div>

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