<?php 
/**
 * Contacts/Enquiries Management System - Full CRUD
 * Location: /college/orc_sch/contacts.php
 * Table: contacts_sch
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// Database connection
require_once '../db.php';

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

$school_id = 3; // Mumbai University ID
$admin_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'Admin';
$page_title = "Contacts Management - Mumbai University";

// ==================== CREATE - ADD NEW CONTACT/ENQUIRY ====================
if (isset($_POST['add_contact'])) {
    $enquiry_type = mysqli_real_escape_string($db, $_POST['enquiry_type']);
    $name = mysqli_real_escape_string($db, $_POST['name']);
    $email = mysqli_real_escape_string($db, $_POST['email']);
    $phone = mysqli_real_escape_string($db, $_POST['phone']);
    $subject = mysqli_real_escape_string($db, $_POST['subject']);
    $message = mysqli_real_escape_string($db, $_POST['message']);
    $course_interest = mysqli_real_escape_string($db, $_POST['course_interest']);
    $year_interest = mysqli_real_escape_string($db, $_POST['year_interest']);
    $city = mysqli_real_escape_string($db, $_POST['city']);
    $state = mysqli_real_escape_string($db, $_POST['state']);
    $priority = mysqli_real_escape_string($db, $_POST['priority']);
    $source = mysqli_real_escape_string($db, $_POST['source']);
    $is_subscribed = isset($_POST['is_subscribed']) ? 1 : 0;
    
    // Get IP Address and User Agent
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = mysqli_real_escape_string($db, $_SERVER['HTTP_USER_AGENT']);
    
    $insert_query = "INSERT INTO contacts_sch 
                     (school_id, enquiry_type, name, email, phone, subject, message, course_interest, 
                      year_interest, city, state, priority, source, is_subscribed, ip_address, user_agent, created_at) 
                     VALUES 
                     ($school_id, '$enquiry_type', '$name', '$email', '$phone', '$subject', '$message', 
                      '$course_interest', '$year_interest', '$city', '$state', '$priority', '$source', 
                      $is_subscribed, '$ip_address', '$user_agent', NOW())";
    
    if (mysqli_query($db, $insert_query)) {
        $success_message = "Contact/Enquiry submitted successfully! Reference ID: " . mysqli_insert_id($db);
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== UPDATE - REPLY TO CONTACT ====================
if (isset($_POST['reply_contact'])) {
    $contact_id = (int)$_POST['contact_id'];
    $status = mysqli_real_escape_string($db, $_POST['status']);
    $priority = mysqli_real_escape_string($db, $_POST['priority']);
    $assigned_to = mysqli_real_escape_string($db, $_POST['assigned_to']);
    $admin_remarks = mysqli_real_escape_string($db, $_POST['admin_remarks']);
    $reply_message = mysqli_real_escape_string($db, $_POST['reply_message']);
    
    $reply_fields = "";
    if (!empty($reply_message)) {
        $reply_fields = ", replied_by = '$admin_name', replied_at = NOW()";
    }
    
    $update_query = "UPDATE contacts_sch 
                     SET status = '$status',
                         priority = '$priority',
                         assigned_to = '$assigned_to',
                         admin_remarks = '$admin_remarks',
                         reply_message = '$reply_message'
                         $reply_fields
                     WHERE id = $contact_id AND school_id = $school_id";
    
    if (mysqli_query($db, $update_query)) {
        $success_message = "Contact updated successfully!";
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== DELETE - REMOVE CONTACT ====================
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    
    $delete_query = "DELETE FROM contacts_sch WHERE id = $delete_id AND school_id = $school_id";
    if (mysqli_query($db, $delete_query)) {
        $success_message = "Contact deleted successfully!";
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== MARK AS READ ====================
if (isset($_GET['mark_read'])) {
    $contact_id = (int)$_GET['mark_read'];
    mysqli_query($db, "UPDATE contacts_sch SET status = 'read' WHERE id = $contact_id AND status = 'new'");
    header("Location: contacts.php");
    exit;
}

// ==================== READ - GET ALL CONTACTS ====================
$filter_status = isset($_GET['status']) ? mysqli_real_escape_string($db, $_GET['status']) : 'all';
$filter_type = isset($_GET['type']) ? mysqli_real_escape_string($db, $_GET['type']) : 'all';
$filter_priority = isset($_GET['priority']) ? mysqli_real_escape_string($db, $_GET['priority']) : 'all';
$search = isset($_GET['search']) ? mysqli_real_escape_string($db, $_GET['search']) : '';

$where_clause = "WHERE school_id = $school_id";

if ($filter_status != 'all') {
    $where_clause .= " AND status = '$filter_status'";
}

if ($filter_type != 'all') {
    $where_clause .= " AND enquiry_type = '$filter_type'";
}

if ($filter_priority != 'all') {
    $where_clause .= " AND priority = '$filter_priority'";
}

if (!empty($search)) {
    $where_clause .= " AND (name LIKE '%$search%' OR email LIKE '%$search%' OR phone LIKE '%$search%' OR subject LIKE '%$search%' OR message LIKE '%$search%')";
}

$contacts_query = "SELECT * FROM contacts_sch $where_clause ORDER BY 
                   FIELD(status, 'new', 'read', 'replied', 'resolved', 'closed'),
                   FIELD(priority, 'urgent', 'high', 'medium', 'low'),
                   id DESC";
$contacts_result = mysqli_query($db, $contacts_query);
$total_contacts = $contacts_result ? mysqli_num_rows($contacts_result) : 0;

// Get contact for viewing
$view_contact = null;
if (isset($_GET['view_id'])) {
    $view_id = (int)$_GET['view_id'];
    $view_query = "SELECT * FROM contacts_sch WHERE id = $view_id AND school_id = $school_id";
    $view_result = mysqli_query($db, $view_query);
    $view_contact = mysqli_fetch_assoc($view_result);
    
    // Auto mark as read
    if ($view_contact && $view_contact['status'] == 'new') {
        mysqli_query($db, "UPDATE contacts_sch SET status = 'read' WHERE id = $view_id");
        $view_contact['status'] = 'read';
    }
}

// Get statistics
$stats_query = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'new' THEN 1 ELSE 0 END) as new_contacts,
                SUM(CASE WHEN status = 'replied' THEN 1 ELSE 0 END) as replied,
                SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved,
                SUM(CASE WHEN enquiry_type = 'admission' THEN 1 ELSE 0 END) as admissions,
                SUM(CASE WHEN priority = 'urgent' THEN 1 ELSE 0 END) as urgent
                FROM contacts_sch WHERE school_id = $school_id";
$stats_result = mysqli_query($db, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);

// Get current page
$current_page = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <style>
/* ==================== CONTACTS MANAGEMENT STYLES ==================== */

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: #f5f6fa;
    color: #2c3e50;
}

/* Sidebar */
.sidebar {
    position: fixed;
    left: 0;
    top: 0;
    width: 260px;
    height: 100vh;
    background: linear-gradient(180deg, #2c3e50 0%, #34495e 100%);
    color: white;
    padding: 20px 0;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 2px 0 10px rgba(0,0,0,0.1);
}

.sidebar-header {
    padding: 20px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    margin-bottom: 20px;
}

.sidebar-header h2 {
    font-size: 1.3em;
    font-weight: 600;
}

.sidebar-menu {
    padding: 0 10px;
}

.menu-item {
    display: block;
    padding: 12px 20px;
    color: #ecf0f1;
    text-decoration: none;
    border-radius: 8px;
    margin-bottom: 5px;
    transition: all 0.3s ease;
    font-size: 0.95em;
}

.menu-item:hover {
    background: rgba(255,255,255,0.1);
    padding-left: 25px;
}

.menu-item.active {
    background: #3498db;
    font-weight: 600;
}

/* Main Content */
.main-content-area {
    margin-left: 260px;
    padding: 30px;
    min-height: 100vh;
}

.page-header {
    background: white;
    padding: 25px 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.page-header h2 {
    color: #2c3e50;
    font-size: 1.8em;
}

.btn-add {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 12px 25px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
    font-size: 0.9em;
}

.btn-add:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

/* Statistics Cards */
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5em;
    color: white;
}

.stat-icon.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.new { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.replied { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.resolved { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.stat-icon.admission { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.stat-icon.urgent { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%); }

.stat-info h3 {
    font-size: 1.8em;
    color: #2c3e50;
    margin-bottom: 5px;
}

.stat-info p {
    color: #7f8c8d;
    font-size: 0.9em;
}

/* Filter Bar */
.filter-bar {
    background: white;
    padding: 20px 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
}

.filter-row {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    align-items: center;
}

.search-box {
    flex: 1;
    min-width: 200px;
}

.search-box input {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 0.95em;
}

.filter-box select {
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 0.95em;
    min-width: 150px;
}

.btn-search {
    background: #3498db;
    color: white;
    padding: 10px 25px;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
}

/* Alert Messages */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-weight: 500;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

/* Form Container */
.form-container {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
}

.form-container h3 {
    margin-bottom: 25px;
    color: #2c3e50;
    font-size: 1.4em;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.form-row-3 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group.full-width {
    grid-column: 1 / -1;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #2c3e50;
    font-size: 0.95em;
}

.form-control {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 1em;
    transition: border 0.3s ease;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

textarea.form-control {
    resize: vertical;
    min-height: 100px;
    font-family: inherit;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: normal;
    cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.btn-submit {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    color: white;
    padding: 12px 30px;
    border: none;
    border-radius: 8px;
    font-size: 1em;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.btn-cancel {
    background: #95a5a6;
    color: white;
    padding: 12px 30px;
    border: none;
    border-radius: 8px;
    font-size: 1em;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-block;
    margin-left: 10px;
}

.btn-cancel:hover {
    background: #7f8c8d;
}

/* Contacts Table */
.contacts-container {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.contacts-container h3 {
    margin-bottom: 25px;
    color: #2c3e50;
    font-size: 1.4em;
}

.table-responsive {
    overflow-x: auto;
}

.contacts-table {
    width: 100%;
    border-collapse: collapse;
}

.contacts-table thead {
    background: #f8f9fa;
}

.contacts-table th {
    padding: 12px;
    text-align: left;
    font-weight: 600;
    color: #2c3e50;
    border-bottom: 2px solid #dee2e6;
    font-size: 0.9em;
}

.contacts-table td {
    padding: 12px;
    border-bottom: 1px solid #dee2e6;
    font-size: 0.9em;
}

.contacts-table tbody tr:hover {
    background: #f8f9fa;
}

.contacts-table tbody tr.unread {
    background: #fff3cd;
}

.badge {
    display: inline-block;
    padding: 5px 12px;
    border-radius: 15px;
    font-size: 0.8em;
    font-weight: 600;
}

.badge-new {
    background: #fff3cd;
    color: #856404;
}

.badge-read {
    background: #cfe2ff;
    color: #084298;
}

.badge-replied {
    background: #d1e7dd;
    color: #0f5132;
}

.badge-resolved {
    background: #d3f9d8;
    color: #0a3622;
}

.badge-closed {
    background: #e2e3e5;
    color: #41464b;
}

.badge-urgent {
    background: #f8d7da;
    color: #842029;
}

.badge-high {
    background: #fff3cd;
    color: #856404;
}

.badge-medium {
    background: #cfe2ff;
    color: #084298;
}

.badge-low {
    background: #d1e7dd;
    color: #0f5132;
}

.btn-action {
    padding: 6px 12px;
    border-radius: 6px;
    text-decoration: none;
    font-size: 0.85em;
    font-weight: 500;
    transition: all 0.3s ease;
    margin-right: 5px;
    display: inline-block;
}

.btn-view {
    background: #17a2b8;
    color: white;
}

.btn-delete {
    background: #e74c3c;
    color: white;
}

.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 3px 10px rgba(0,0,0,0.2);
}

.no-data {
    text-align: center;
    padding: 60px 20px;
    color: #7f8c8d;
}

.no-data-icon {
    font-size: 4em;
    margin-bottom: 20px;
}

/* View Contact Detail */
.contact-detail {
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 30px;
}

.contact-header {
    border-bottom: 2px solid #e9ecef;
    padding-bottom: 20px;
    margin-bottom: 20px;
}

.contact-id {
    color: #7f8c8d;
    font-size: 0.9em;
}

.contact-subject {
    font-size: 1.5em;
    color: #2c3e50;
    margin: 10px 0;
}

.contact-meta {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    margin-top: 15px;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #7f8c8d;
    font-size: 0.9em;
}

.contact-body {
    margin-bottom: 30px;
}

.info-section {
    margin-bottom: 25px;
}

.info-section h4 {
    color: #2c3e50;
    margin-bottom: 15px;
    font-size: 1.1em;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

.info-item {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.info-label {
    color: #7f8c8d;
    font-size: 0.85em;
    font-weight: 600;
}

.info-value {
    color: #2c3e50;
    font-size: 0.95em;
}

.message-box {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border-left: 4px solid #3498db;
    line-height: 1.6;
}

.remarks-box {
    background: #fff3cd;
    padding: 20px;
    border-radius: 8px;
    border-left: 4px solid #ffc107;
    line-height: 1.6;
}

.reply-box {
    background: #d1e7dd;
    padding: 20px;
    border-radius: 8px;
    border-left: 4px solid #28a745;
    line-height: 1.6;
}

/* Responsive */
@media (max-width: 768px) {
    .sidebar {
        width: 100%;
        height: auto;
        position: relative;
    }
    
    .main-content-area {
        margin-left: 0;
        padding: 15px;
    }
    
    .page-header {
        flex-direction: column;
        text-align: center;
    }
    
    .stats-container {
        grid-template-columns: 1fr;
    }
    
    .filter-row {
        flex-direction: column;
    }
    
    .form-row,
    .form-row-3,
    .info-grid {
        grid-template-columns: 1fr;
    }
}
    </style>
</head>
<body>

<!-- SIDEBAR -->
<div class="sidebar">
    <div class="sidebar-header">
        <h2>📚 Mumbai University</h2>
    </div>
    <nav class="sidebar-menu">
        <a href="/college/orc_sch/dashbored1.php" class="menu-item <?php echo $current_page == 'dashbored1.php' ? 'active' : ''; ?>">🏠 Dashboard</a>
        <a href="/college/orc_sch/course.php" class="menu-item <?php echo $current_page == 'course.php' ? 'active' : ''; ?>">📚 Course</a>
        <a href="/college/orc_sch/teachers.php" class="menu-item <?php echo $current_page == 'teachers.php' ? 'active' : ''; ?>">👨‍🏫 Teachers</a>
        <a href="/college/orc_sch/complaint.php" class="menu-item <?php echo ($current_page == 'complaint.php') ? 'active' : ''; ?>">👨‍🏫Complaint</a>
        <a href="/college/orc_sch/gallery.php" class="menu-item <?php echo $current_page == 'gallery.php' ? 'active' : ''; ?>">🖼️ Gallery</a>
        <a href="/college/orc_sch/contact.php" class="menu-item <?php echo $current_page == 'contact.php' ? 'active' : ''; ?>">📧 Contact</a>
        <a href="/college/orc_sch/logout.php" class="menu-item <?php echo ($current_page == 'logout.php') ? 'active' : ''; ?>">🚪Logout</a>
    </nav>
</div>

<!-- MAIN CONTENT -->
<div class="main-content-area">
    
    <!-- Page Header -->
    <div class="page-header">
        <h2>📧 Contacts & Enquiries (<?php echo $total_contacts; ?>)</h2>
        <?php if (!isset($_GET['view_id'])): ?>
            <button class="btn-add" onclick="document.getElementById('add-form').style.display='block'; window.scrollTo(0,0);">➕ Add Contact</button>
        <?php endif; ?>
    </div>

    <!-- Success/Error Messages -->
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success">✓ <?php echo $success_message; ?></div>
    <?php endif; ?>
    
    <?php if (isset($error_message)): ?>
        <div class="alert alert-error">✗ <?php echo $error_message; ?></div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <?php if (!isset($_GET['view_id'])): ?>
    <div class="stats-container">
        <div class="stat-card">
            <div class="stat-icon total">📊</div>
            <div class="stat-info">
                <h3><?php echo $stats['total']; ?></h3>
                <p>Total Contacts</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon new">🆕</div>
            <div class="stat-info">
                <h3><?php echo $stats['new_contacts']; ?></h3>
                <p>New</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon replied">💬</div>
            <div class="stat-info">
                <h3><?php echo $stats['replied']; ?></h3>
                <p>Replied</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon resolved">✅</div>
            <div class="stat-info">
                <h3><?php echo $stats['resolved']; ?></h3>
                <p>Resolved</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon admission">🎓</div>
            <div class="stat-info">
                <h3><?php echo $stats['admissions']; ?></h3>
                <p>Admissions</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon urgent">🚨</div>
            <div class="stat-info">
                <h3><?php echo $stats['urgent']; ?></h3>
                <p>Urgent</p>
            </div>
        </div>
    </div>

    <!-- Filter Bar -->
    <div class="filter-bar">
        <form method="GET" class="filter-row">
            <div class="search-box">
                <input type="text" name="search" placeholder="🔍 Search by name, email, phone, subject..." 
                       value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="filter-box">
                <select name="status" onchange="this.form.submit()">
                    <option value="all" <?php echo $filter_status == 'all' ? 'selected' : ''; ?>>All Status</option>
                    <option value="new" <?php echo $filter_status == 'new' ? 'selected' : ''; ?>>New</option>
                    <option value="read" <?php echo $filter_status == 'read' ? 'selected' : ''; ?>>Read</option>
                    <option value="replied" <?php echo $filter_status == 'replied' ? 'selected' : ''; ?>>Replied</option>
                    <option value="resolved" <?php echo $filter_status == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                    <option value="closed" <?php echo $filter_status == 'closed' ? 'selected' : ''; ?>>Closed</option>
                </select>
            </div>
            <div class="filter-box">
                <select name="type" onchange="this.form.submit()">
                    <option value="all" <?php echo $filter_type == 'all' ? 'selected' : ''; ?>>All Types</option>
                    <option value="admission" <?php echo $filter_type == 'admission' ? 'selected' : ''; ?>>Admission</option>
                    <option value="course" <?php echo $filter_type == 'course' ? 'selected' : ''; ?>>Course</option>
                    <option value="placement" <?php echo $filter_type == 'placement' ? 'selected' : ''; ?>>Placement</option>
                    <option value="general" <?php echo $filter_type == 'general' ? 'selected' : ''; ?>>General</option>
                    <option value="complaint" <?php echo $filter_type == 'complaint' ? 'selected' : ''; ?>>Complaint</option>
                    <option value="feedback" <?php echo $filter_type == 'feedback' ? 'selected' : ''; ?>>Feedback</option>
                    <option value="support" <?php echo $filter_type == 'support' ? 'selected' : ''; ?>>Support</option>
                    <option value="other" <?php echo $filter_type == 'other' ? 'selected' : ''; ?>>Other</option>
                </select>
            </div>
            <div class="filter-box">
                <select name="priority" onchange="this.form.submit()">
                    <option value="all" <?php echo $filter_priority == 'all' ? 'selected' : ''; ?>>All Priority</option>
                    <option value="urgent" <?php echo $filter_priority == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                    <option value="high" <?php echo $filter_priority == 'high' ? 'selected' : ''; ?>>High</option>
                    <option value="medium" <?php echo $filter_priority == 'medium' ? 'selected' : ''; ?>>Medium</option>
                    <option value="low" <?php echo $filter_priority == 'low' ? 'selected' : ''; ?>>Low</option>
                </select>
            </div>
            <button type="submit" class="btn-search">Search</button>
        </form>
    </div>
    <?php endif; ?>

    <!-- Add Contact Form -->
    <?php if (!isset($_GET['view_id'])): ?>
    <div class="form-container" id="add-form" style="display:none;">
        <h3>➕ Add New Contact/Enquiry</h3>
        <form method="POST">
            
            <div class="form-row">
                <div class="form-group">
                    <label>Enquiry Type *</label>
                    <select name="enquiry_type" class="form-control" required>
                        <option value="general">📋 General Enquiry</option>
                        <option value="admission">🎓 Admission</option>
                        <option value="course">📚 Course Information</option>
                        <option value="placement">💼 Placement</option>
                        <option value="complaint">⚠️ Complaint</option>
                        <option value="feedback">💬 Feedback</option>
                        <option value="support">🛠️ Technical Support</option>
                        <option value="other">📝 Other</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Priority</label>
                    <select name="priority" class="form-control">
                        <option value="low">🟢 Low</option>
                        <option value="medium" selected>🟡 Medium</option>
                        <option value="high">🟠 High</option>
                        <option value="urgent">🔴 Urgent</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Full Name *</label>
                    <input type="text" name="name" class="form-control" required placeholder="Enter full name">
                </div>

                <div class="form-group">
                    <label>Email Address *</label>
                    <input type="email" name="email" class="form-control" required placeholder="your.email@example.com">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="tel" name="phone" class="form-control" placeholder="10-digit mobile number">
                </div>

                <div class="form-group">
                    <label>Source</label>
                    <select name="source" class="form-control">
                        <option value="website" selected>🌐 Website</option>
                        <option value="phone">📞 Phone</option>
                        <option value="email">📧 Email</option>
                        <option value="walk-in">🚶 Walk-in</option>
                        <option value="social-media">📱 Social Media</option>
                        <option value="other">📝 Other</option>
                    </select>
                </div>
            </div>

            <div class="form-group full-width">
                <label>Subject *</label>
                <input type="text" name="subject" class="form-control" required placeholder="Brief subject of enquiry">
            </div>

            <div class="form-group full-width">
                <label>Message *</label>
                <textarea name="message" class="form-control" rows="4" required placeholder="Write your detailed message here..."></textarea>
            </div>

            <div class="form-row-3">
                <div class="form-group">
                    <label>Course Interest</label>
                    <input type="text" name="course_interest" class="form-control" placeholder="e.g. B.Tech CS">
                </div>

                <div class="form-group">
                    <label>Year of Interest</label>
                    <input type="text" name="year_interest" class="form-control" placeholder="e.g. 2026">
                </div>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_subscribed" value="1">
                        <span>📬 Subscribe to Newsletter</span>
                    </label>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>City</label>
                    <input type="text" name="city" class="form-control" placeholder="Your city">
                </div>

                <div class="form-group">
                    <label>State</label>
                    <input type="text" name="state" class="form-control" placeholder="Your state">
                </div>
            </div>

            <div style="margin-top: 20px;">
                <button type="submit" name="add_contact" class="btn-submit">📤 Submit Enquiry</button>
                <button type="button" class="btn-cancel" onclick="document.getElementById('add-form').style.display='none';">✕ Cancel</button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- View/Reply Contact -->
    <?php if ($view_contact): ?>
    <div class="contact-detail">
        <div class="contact-header">
            <div class="contact-id">Contact ID: #<?php echo $view_contact['id']; ?></div>
            <h2 class="contact-subject"><?php echo htmlspecialchars($view_contact['subject']); ?></h2>
            <div class="contact-meta">
                <div class="meta-item">
                    <strong>Type:</strong>
                    <span class="badge"><?php echo ucfirst($view_contact['enquiry_type']); ?></span>
                </div>
                <div class="meta-item">
                    <strong>Status:</strong>
                    <span class="badge badge-<?php echo $view_contact['status']; ?>"><?php echo ucfirst($view_contact['status']); ?></span>
                </div>
                <div class="meta-item">
                    <strong>Priority:</strong>
                    <span class="badge badge-<?php echo $view_contact['priority']; ?>"><?php echo ucfirst($view_contact['priority']); ?></span>
                </div>
                <div class="meta-item">
                    <strong>Received:</strong> <?php echo date('d M Y, h:i A', strtotime($view_contact['created_at'])); ?>
                </div>
            </div>
        </div>

        <div class="contact-body">
            <!-- Message -->
            <div class="info-section">
                <h4>📩 Message</h4>
                <div class="message-box">
                    <?php echo nl2br(htmlspecialchars($view_contact['message'])); ?>
                </div>
            </div>

            <!-- Contact Details -->
            <div class="info-section">
                <h4>👤 Contact Details</h4>
                <div class="info-grid">
                    <div class="info-item">
                        <span class="info-label">Name</span>
                        <span class="info-value"><?php echo htmlspecialchars($view_contact['name']); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Email</span>
                        <span class="info-value"><?php echo htmlspecialchars($view_contact['email']); ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Phone</span>
                        <span class="info-value"><?php echo $view_contact['phone'] ? htmlspecialchars($view_contact['phone']) : 'N/A'; ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Location</span>
                        <span class="info-value"><?php echo $view_contact['city'] ? htmlspecialchars($view_contact['city']) . ', ' . htmlspecialchars($view_contact['state']) : 'N/A'; ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Course Interest</span>
                        <span class="info-value"><?php echo $view_contact['course_interest'] ? htmlspecialchars($view_contact['course_interest']) : 'N/A'; ?></span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Source</span>
                        <span class="info-value"><?php echo ucfirst(str_replace('-', ' ', $view_contact['source'])); ?></span>
                    </div>
                </div>
            </div>

            <!-- Admin Remarks -->
            <?php if (!empty($view_contact['admin_remarks'])): ?>
            <div class="info-section">
                <h4>📝 Admin Remarks</h4>
                <div class="remarks-box">
                    <?php echo nl2br(htmlspecialchars($view_contact['admin_remarks'])); ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Reply -->
            <?php if (!empty($view_contact['reply_message'])): ?>
            <div class="info-section">
                <h4>💬 Reply Sent</h4>
                <div class="reply-box">
                    <?php echo nl2br(htmlspecialchars($view_contact['reply_message'])); ?>
                    <?php if ($view_contact['replied_by']): ?>
                        <div style="margin-top: 15px; font-size: 0.9em;">
                            <strong>Replied by:</strong> <?php echo htmlspecialchars($view_contact['replied_by']); ?><br>
                            <strong>Replied on:</strong> <?php echo date('d M Y, h:i A', strtotime($view_contact['replied_at'])); ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Reply Form -->
        <div class="info-section">
            <h4>✉️ Reply to Contact</h4>
            <form method="POST">
                <input type="hidden" name="contact_id" value="<?php echo $view_contact['id']; ?>">
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Status *</label>
                        <select name="status" class="form-control" required>
                            <option value="new" <?php echo $view_contact['status'] == 'new' ? 'selected' : ''; ?>>New</option>
                            <option value="read" <?php echo $view_contact['status'] == 'read' ? 'selected' : ''; ?>>Read</option>
                            <option value="replied" <?php echo $view_contact['status'] == 'replied' ? 'selected' : ''; ?>>Replied</option>
                            <option value="resolved" <?php echo $view_contact['status'] == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                            <option value="closed" <?php echo $view_contact['status'] == 'closed' ? 'selected' : ''; ?>>Closed</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Priority</label>
                        <select name="priority" class="form-control">
                            <option value="low" <?php echo $view_contact['priority'] == 'low' ? 'selected' : ''; ?>>Low</option>
                            <option value="medium" <?php echo $view_contact['priority'] == 'medium' ? 'selected' : ''; ?>>Medium</option>
                            <option value="high" <?php echo $view_contact['priority'] == 'high' ? 'selected' : ''; ?>>High</option>
                            <option value="urgent" <?php echo $view_contact['priority'] == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label>Assigned To</label>
                    <input type="text" name="assigned_to" class="form-control" 
                           value="<?php echo htmlspecialchars($view_contact['assigned_to']); ?>"
                           placeholder="Staff/Department name">
                </div>

                <div class="form-group">
                    <label>Admin Remarks (Internal)</label>
                    <textarea name="admin_remarks" class="form-control" rows="3"><?php echo htmlspecialchars($view_contact['admin_remarks']); ?></textarea>
                </div>

                <div class="form-group">
                    <label>Reply Message (Sent to User)</label>
                    <textarea name="reply_message" class="form-control" rows="4" placeholder="Write your reply here..."><?php echo htmlspecialchars($view_contact['reply_message']); ?></textarea>
                </div>

                <div style="margin-top: 20px;">
                    <button type="submit" name="reply_contact" class="btn-submit">📤 Send Reply & Update</button>
                    <a href="contacts.php" class="btn-cancel">← Back</a>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <!-- Contacts Table -->
    <?php if (!isset($_GET['view_id'])): ?>
    <div class="contacts-container">
        <h3>📋 All Contacts & Enquiries</h3>

        <?php if ($total_contacts > 0): ?>
            <div class="table-responsive">
                <table class="contacts-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Type</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Subject</th>
                            <th>Priority</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($contact = mysqli_fetch_assoc($contacts_result)): ?>
                            <tr class="<?php echo $contact['status'] == 'new' ? 'unread' : ''; ?>">
                                <td>#<?php echo $contact['id']; ?></td>
                                <td><span class="badge"><?php echo ucfirst($contact['enquiry_type']); ?></span></td>
                                <td><?php echo htmlspecialchars($contact['name']); ?></td>
                                <td><?php echo htmlspecialchars($contact['email']); ?></td>
                                <td style="max-width: 250px;"><strong><?php echo htmlspecialchars(substr($contact['subject'], 0, 40)); ?><?php echo strlen($contact['subject']) > 40 ? '...' : ''; ?></strong></td>
                                <td><span class="badge badge-<?php echo $contact['priority']; ?>"><?php echo ucfirst($contact['priority']); ?></span></td>
                                <td><span class="badge badge-<?php echo $contact['status']; ?>"><?php echo ucfirst($contact['status']); ?></span></td>
                                <td><?php echo date('d M Y', strtotime($contact['created_at'])); ?></td>
                                <td>
                                    <a href="?view_id=<?php echo $contact['id']; ?>" class="btn-action btn-view">👁️</a>
                                    <a href="?delete_id=<?php echo $contact['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Delete this contact?')">🗑️</a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="no-data">
                <div class="no-data-icon">📧</div>
                <p style="font-size: 1.2em; font-weight: 600;">No contacts found</p>
                <p style="margin-top: 10px;">Click "Add Contact" button above!</p>
            </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

</div>

</body>
</html>
