<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';

$msg = "";
$edit_mode = false;
$doctor_data = [
    'id' => '', 'name' => '', 'qualification' => '', 'speciality' => '', 'bio' => '', 'image_url' => ''
];

// --- 1. HANDLE FORM SUBMISSION (ADD OR UPDATE) ---
if (isset($_POST['save_doctor'])) {
    $name = $conn->real_escape_string($_POST['name']);
    $qual = $conn->real_escape_string($_POST['qualification']);
    $spec = $conn->real_escape_string($_POST['speciality']);
    $bio  = $conn->real_escape_string($_POST['bio']);
    
    // Check if updating or adding new
    $doc_id = $_POST['doctor_id'];
    
    // Image Upload Logic
    $image_query_part = "";
    if (!empty($_FILES["photo"]["name"])) {
        $target_dir = "../assets/";
        $file_name = time() . "_" . basename($_FILES["photo"]["name"]);
        $target_file = $target_dir . $file_name;
        
        if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file)) {
            $image_query_part = ", image_url='$file_name'";
        } else {
            $msg = "Error uploading image.";
        }
    }

    if (!empty($doc_id)) {
        // UPDATE EXISTING DOCTOR
        $sql = "UPDATE doctors SET name='$name', qualification='$qual', speciality='$spec', bio='$bio' $image_query_part WHERE id=$doc_id";
        if ($conn->query($sql)) {
            $msg = "Doctor Updated Successfully!";
            // Reset form after update
            $doc_id = ""; 
        } else {
            $msg = "Error updating record: " . $conn->error;
        }
    } else {
        // INSERT NEW DOCTOR
        // For new insert, image is required if not handled differently, but here we assume file_name is set if uploaded
        $img_val = isset($file_name) ? $file_name : 'default.jpg';
        $sql = "INSERT INTO doctors (name, qualification, speciality, bio, image_url) VALUES ('$name', '$qual', '$spec', '$bio', '$img_val')";
        if ($conn->query($sql)) {
            $msg = "Doctor Added Successfully!";
        } else {
            $msg = "Error adding record: " . $conn->error;
        }
    }
}

// --- 2. HANDLE DELETE ---
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM doctors WHERE id=$id");
    header("Location: doctors.php");
    exit();
}

// --- 3. HANDLE EDIT CLICK (FETCH DATA) ---
if (isset($_GET['edit'])) {
    $edit_mode = true;
    $id = intval($_GET['edit']);
    $res = $conn->query("SELECT * FROM doctors WHERE id=$id");
    if($res->num_rows > 0) {
        $doctor_data = $res->fetch_assoc();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Doctors</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-6">
    <nav class="mb-6 flex gap-4 items-center">
        <a href="dashboard.php" class="text-blue-600 font-bold hover:underline">← Back to Dashboard</a>
        <?php if($edit_mode): ?>
            <a href="doctors.php" class="bg-gray-500 text-white px-3 py-1 rounded text-sm">Cancel Edit</a>
        <?php endif; ?>
    </nav>

    <div class="grid md:grid-cols-3 gap-8">
        
        <!-- FORM SECTION (ADD / EDIT) -->
        <div class="bg-white p-6 rounded shadow-md h-fit border-t-4 <?php echo $edit_mode ? 'border-yellow-500' : 'border-teal-500'; ?>">
            <h2 class="text-xl font-bold mb-4">
                <?php echo $edit_mode ? '✏️ Edit Doctor' : '➕ Add New Doctor'; ?>
            </h2>
            
            <?php if($msg) echo "<p class='bg-green-100 text-green-700 p-2 rounded mb-4 text-sm'>$msg</p>"; ?>
            
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <!-- Hidden ID field to track edit state -->
                <input type="hidden" name="doctor_id" value="<?php echo $doctor_data['id']; ?>">

                <div>
                    <label class="block text-sm text-gray-600 font-bold">Doctor Name</label>
                    <input type="text" name="name" value="<?php echo $doctor_data['name']; ?>" placeholder="e.g. Dr. Name Surname" required class="w-full border p-2 rounded">
                </div>
                
                <div>
                    <label class="block text-sm text-gray-600 font-bold">Qualifications</label>
                    <input type="text" name="qualification" value="<?php echo $doctor_data['qualification']; ?>" placeholder="e.g. MBBS, MS" required class="w-full border p-2 rounded">
                </div>
                
                <div>
                    <label class="block text-sm text-gray-600 font-bold">Speciality / Tags</label>
                    <input type="text" name="speciality" value="<?php echo $doctor_data['speciality']; ?>" placeholder="e.g. Surgery, Hernia" required class="w-full border p-2 rounded">
                </div>

                <div>
                    <label class="block text-sm text-gray-600 font-bold">Biography (Detailed Profile)</label>
                    <textarea name="bio" rows="5" class="w-full border p-2 rounded" placeholder="Write about the doctor's experience and approach..."><?php echo $doctor_data['bio']; ?></textarea>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-600 font-bold">Photo</label>
                    <?php if($edit_mode && !empty($doctor_data['image_url'])): ?>
                        <div class="flex items-center gap-2 mb-2">
                            <img src="../assets/<?php echo $doctor_data['image_url']; ?>" class="w-10 h-10 rounded-full object-cover">
                            <span class="text-xs text-gray-400">Current Image</span>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="photo" class="w-full border p-2 rounded text-sm text-gray-500">
                    <p class="text-xs text-gray-400 mt-1">Leave empty to keep current photo.</p>
                </div>
                
                <button type="submit" name="save_doctor" class="w-full text-white font-bold py-2 rounded hover:opacity-90 transition <?php echo $edit_mode ? 'bg-yellow-500' : 'bg-teal-600'; ?>">
                    <?php echo $edit_mode ? 'Update Doctor Details' : 'Add Doctor'; ?>
                </button>
            </form>
        </div>

        <!-- LIST SECTION -->
        <div class="md:col-span-2 space-y-4">
            <h2 class="text-xl font-bold text-gray-700">Current Medical Team</h2>
            <?php
            $result = $conn->query("SELECT * FROM doctors ORDER BY id ASC");
            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    // Card Color based on Doctor Name (Visual Aid)
                    $borderColor = (strpos($row['name'], 'Anita') !== false) ? 'border-pink-500' : 'border-teal-500';
                    
                    echo '<div class="bg-white p-4 rounded shadow flex items-start justify-between border-l-4 ' . $borderColor . '">';
                    
                    // Content
                    echo '<div class="flex items-center gap-4">';
                    echo '<img src="../assets/' . $row['image_url'] . '" class="w-16 h-16 rounded-full object-cover border">';
                    echo '<div>';
                    echo '<h3 class="font-bold text-lg text-gray-800">' . $row['name'] . '</h3>';
                    echo '<p class="text-sm font-semibold text-gray-600">' . $row['qualification'] . '</p>';
                    echo '<p class="text-xs text-gray-500">' . $row['speciality'] . '</p>';
                    echo '</div>';
                    echo '</div>';
                    
                    // Buttons
                    echo '<div class="flex flex-col gap-2">';
                    echo '<a href="doctors.php?edit=' . $row['id'] . '" class="bg-blue-100 text-blue-600 px-3 py-1 rounded text-xs font-bold text-center hover:bg-blue-200">Edit</a>';
                    echo '<a href="doctors.php?delete=' . $row['id'] . '" class="bg-red-100 text-red-600 px-3 py-1 rounded text-xs font-bold text-center hover:bg-red-200" onclick="return confirm(\'Delete this doctor? This cannot be undone.\')">Delete</a>';
                    echo '</div>';
                    
                    echo '</div>';
                }
            } else {
                echo "<p class='text-gray-500'>No doctors found. Add one to get started.</p>";
            }
            ?>
        </div>
    </div>
</body>
</html>