<?php
require_once '../includes/config.php';

// Check if user is logged in and is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || $_SESSION['role'] !== 'admin') {
    header('Location: ../auth/login.php');
    exit();
}

$title = "Edit Activity";

// Get activity ID
$activity_id = $_GET['id'] ?? 0;

if ($activity_id <= 0) {
    $_SESSION['message'] = 'Invalid activity ID!';
    $_SESSION['message_type'] = 'danger';
    header('Location: manage_activities.php');
    exit();
}

// Get activity data
$sql = "SELECT * FROM activities WHERE id = $activity_id";
$result = query($conn, $sql);
if (!$result || mysqli_num_rows($result) == 0) {
    $_SESSION['message'] = 'Activity not found!';
    $_SESSION['message_type'] = 'danger';
    header('Location: manage_activities.php');
    exit();
}

$activity = mysqli_fetch_assoc($result);

// Initialize variables
$message = '';
$message_type = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    $required_fields = ['name', 'date', 'time_in', 'time_out', 'location', 'required_students'];
    $valid = true;
    
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $message = "Please fill all required fields!";
            $message_type = 'danger';
            $valid = false;
            break;
        }
    }
    
    if ($valid) {
        $activity_data = [
            'name' => escape($conn, $_POST['name']),
            'date' => $_POST['date'],
            'time_in' => $_POST['time_in'],
            'time_out' => $_POST['time_out'],
            'description' => escape($conn, $_POST['description']),
            'location' => escape($conn, $_POST['location']),
            'required_students' => $_POST['required_students'],
            'course_id' => $_POST['course_id'] ? intval($_POST['course_id']) : null,
            'department_id' => $_POST['department_id'] ? intval($_POST['department_id']) : null,
            'status' => isset($_POST['status']) ? 1 : 0
        ];

        // Validate time
        if (strtotime($activity_data['time_out']) <= strtotime($activity_data['time_in'])) {
            $message = 'Time Out must be later than Time In!';
            $message_type = 'danger';
        } else {
            $sql = "UPDATE activities SET
                name = '{$activity_data['name']}',
                date = '{$activity_data['date']}',
                time_in = '{$activity_data['time_in']}',
                time_out = '{$activity_data['time_out']}',
                description = '{$activity_data['description']}',
                location = '{$activity_data['location']}',
                required_students = '{$activity_data['required_students']}',
                course_id = " . ($activity_data['course_id'] ? $activity_data['course_id'] : 'NULL') . ",
                department_id = " . ($activity_data['department_id'] ? $activity_data['department_id'] : 'NULL') . ",
                status = {$activity_data['status']},
                updated_at = NOW()
                WHERE id = $activity_id";

            if (query($conn, $sql)) {
                $_SESSION['message'] = 'Activity updated successfully!';
                $_SESSION['message_type'] = 'success';
                header('Location: manage_activities.php');
                exit();
            } else {
                $message = 'Error updating activity: ' . mysqli_error($conn);
                $message_type = 'danger';
            }
        }
    }
}

// Get dropdown data
$courses = [];
$departments = [];

// Courses
$result = query($conn, "SELECT * FROM courses WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $courses[] = $row;
}

// Departments
$result = query($conn, "SELECT * FROM departments WHERE status = 1 ORDER BY code");
while ($row = mysqli_fetch_assoc($result)) {
    $departments[] = $row;
}

include '../includes/header.php';
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-2">Edit Activity</h1>
        <p class="text-muted">Update activity details.</p>
    </div>
    <div>
        <a href="manage_activities.php" class="btn btn-secondary">
            <i class="bi bi-arrow-left me-2"></i> Back to Activities
        </a>
    </div>
</div>

<!-- Message Alert -->
<?php if ($message): ?>
<div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Edit Activity Form -->
<div class="card shadow">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-pencil me-2"></i> Edit Activity: <?php echo $activity['name']; ?>
        </h5>
    </div>
    <div class="card-body">
        <form method="POST" action="" id="editActivityForm">
            <input type="hidden" name="activity_id" value="<?php echo $activity['id']; ?>">
            
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="form-label">Activity Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="name" required 
                           value="<?php echo htmlspecialchars($activity['name']); ?>">
                </div>
                
                <div class="col-md-6 mb-3">
                    <label class="form-label">Date <span class="text-danger">*</span></label>
                    <input type="date" class="form-control" name="date" required 
                           value="<?php echo $activity['date']; ?>">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">Time In <span class="text-danger">*</span></label>
                    <input type="time" class="form-control" name="time_in" required 
                           value="<?php echo $activity['time_in']; ?>">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">Time Out <span class="text-danger">*</span></label>
                    <input type="time" class="form-control" name="time_out" required 
                           value="<?php echo $activity['time_out']; ?>">
                </div>
                
                <div class="col-md-12 mb-3">
                    <label class="form-label">Location <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="location" required 
                           value="<?php echo htmlspecialchars($activity['location']); ?>">
                </div>
                
                <div class="col-md-12 mb-3">
                    <label class="form-label">Description</label>
                    <textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars($activity['description']); ?></textarea>
                </div>
                
                <div class="col-md-12 mb-3">
                    <label class="form-label">Participants <span class="text-danger">*</span></label>
                    <select class="form-select" name="required_students" required id="participantType" onchange="toggleParticipantSelection()">
                        <option value="all" <?php echo $activity['required_students'] == 'all' ? 'selected' : ''; ?>>All Students</option>
                        <option value="specific_course" <?php echo $activity['required_students'] == 'specific_course' ? 'selected' : ''; ?>>Specific Course</option>
                        <option value="specific_department" <?php echo $activity['required_students'] == 'specific_department' ? 'selected' : ''; ?>>Specific Department</option>
                    </select>
                </div>
                
                <div class="col-md-6 mb-3" id="courseSelection" style="<?php echo $activity['required_students'] == 'specific_course' ? '' : 'display: none;'; ?>">
                    <label class="form-label">Select Course</label>
                    <select class="form-select" name="course_id" id="courseSelect">
                        <option value="">Select Course</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>"
                                <?php echo $activity['course_id'] == $course['id'] ? 'selected' : ''; ?>>
                                <?php echo $course['code']; ?> - <?php echo $course['name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6 mb-3" id="departmentSelection" style="<?php echo $activity['required_students'] == 'specific_department' ? '' : 'display: none;'; ?>">
                    <label class="form-label">Select Department</label>
                    <select class="form-select" name="department_id" id="departmentSelect">
                        <option value="">Select Department</option>
                        <?php foreach ($departments as $department): ?>
                            <option value="<?php echo $department['id']; ?>"
                                <?php echo $activity['department_id'] == $department['id'] ? 'selected' : ''; ?>>
                                <?php echo $department['name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-12 mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" role="switch" 
                               name="status" id="statusSwitch" value="1"
                               <?php echo $activity['status'] == 1 ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="statusSwitch">
                            Active Activity
                        </label>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save me-1"></i> Update Activity
                </button>
                <a href="manage_activities.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<?php 
$page_scripts = '
<script>
function toggleParticipantSelection() {
    const participantType = document.getElementById("participantType").value;
    const courseSelection = document.getElementById("courseSelection");
    const departmentSelection = document.getElementById("departmentSelection");
    
    if (participantType === "specific_course") {
        courseSelection.style.display = "block";
        departmentSelection.style.display = "none";
        document.getElementById("courseSelect").required = true;
        document.getElementById("departmentSelect").required = false;
    } else if (participantType === "specific_department") {
        courseSelection.style.display = "none";
        departmentSelection.style.display = "block";
        document.getElementById("courseSelect").required = false;
        document.getElementById("departmentSelect").required = true;
    } else {
        courseSelection.style.display = "none";
        departmentSelection.style.display = "none";
        document.getElementById("courseSelect").required = false;
        document.getElementById("departmentSelect").required = false;
    }
}

// Time validation
document.addEventListener("DOMContentLoaded", function() {
    // Initialize participant selection
    toggleParticipantSelection();
    
    document.getElementById("editActivityForm").addEventListener("submit", function(e) {
        const timeIn = document.querySelector("input[name=\'time_in\']").value;
        const timeOut = document.querySelector("input[name=\'time_out\']").value;
        
        if (timeIn && timeOut && timeOut <= timeIn) {
            e.preventDefault();
            alert("Time Out must be later than Time In!");
            return false;
        }
    });
});
</script>
';

include '../includes/footer.php';
?>