<?php 
/**
 * FIXED COMPLETE CONTACTS.PHP - Ready to Deploy in /college/orc_sch/
 * Handles 500 error - Proper error handling, security fixes, complete HTML
 */

// ==================== SECURITY & ERROR HANDLING ====================
error_reporting(E_ALL);
ini_set('display_errors', 0); // Hide errors in production
ini_set('log_errors', 1);

session_start();

// Database connection with error handling
require_once '../db.php';

// Test DB connection
if (!isset($db) || mysqli_connect_errno()) {
    die('Database connection failed. Check db.php');
}

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

$school_id = 3; // Mumbai University
$admin_name = $_SESSION['username'] ?? 'Admin';
$page_title = "Contacts Management";
$current_page = basename($_SERVER['PHP_SELF']);

// ==================== PREPARED STATEMENTS FOR SECURITY ====================
function safe_insert($db, $data) {
    $stmt = mysqli_prepare($db, "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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    mysqli_stmt_bind_param($stmt, "issssssssssssisss", 
        $data['school_id'], $data['enquiry_type'], $data['name'], $data['email'], 
        $data['phone'], $data['subject'], $data['message'], $data['course_interest'],
        $data['year_interest'], $data['city'], $data['state'], $data['priority'],
        $data['source'], $data['is_subscribed'], $data['ip_address'], $data['user_agent']);
    return mysqli_stmt_execute($stmt);
}

// ==================== PROCESS FORMS ====================
$messages = [];

if ($_POST['add_contact'] ?? false) {
    $data = [
        'school_id' => $school_id,
        'enquiry_type' => $_POST['enquiry_type'],
        'name' => $_POST['name'],
        'email' => $_POST['email'],
        'phone' => $_POST['phone'],
        'subject' => $_POST['subject'],
        'message' => $_POST['message'],
        'course_interest' => $_POST['course_interest'],
        'year_interest' => $_POST['year_interest'],
        'city' => $_POST['city'],
        'state' => $_POST['state'],
        'priority' => $_POST['priority'],
        'source' => $_POST['source'],
        'is_subscribed' => $_POST['is_subscribed'] ?? 0,
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'user_agent' => $_SERVER['HTTP_USER_AGENT']
    ];
    
    if (safe_insert($db, $data)) {
        $messages[] = ['type' => 'success', 'text' => 'Contact added! ID: ' . mysqli_insert_id($db)];
    } else {
        $messages[] = ['type' => 'error', 'text' => 'Failed to add contact'];
    }
}

if ($_POST['reply_contact'] ?? false) {
    $contact_id = (int)$_POST['contact_id'];
    $stmt = mysqli_prepare($db, "UPDATE contacts_sch SET status=?, priority=?, assigned_to=?, admin_remarks=?, reply_message=?, replied_by=?, replied_at=NOW() WHERE id=? AND school_id=?");
    mysqli_stmt_bind_param($stmt, "ssssssii", $_POST['status'], $_POST['priority'], $_POST['assigned_to'], $_POST['admin_remarks'], $_POST['reply_message'], $admin_name, $contact_id, $school_id);
    if (mysqli_stmt_execute($stmt)) {
        $messages[] = ['type' => 'success', 'text' => 'Contact updated!'];
    } else {
        $messages[] = ['type' => 'error', 'text' => 'Update failed'];
    }
}

// ==================== FILTER & QUERY ====================
$filter_status = $_GET['status'] ?? 'all';
$filter_type = $_GET['type'] ?? 'all';
$filter_priority = $_GET['priority'] ?? 'all';
$search = $_GET['search'] ?? '';

$where = "WHERE school_id = ?";
$params = [$school_id];
$types = "i";

if ($filter_status !== 'all') { $where .= " AND status = ?"; $params[] = $filter_status; $types .= "s"; }
if ($filter_type !== 'all') { $where .= " AND enquiry_type = ?"; $params[] = $filter_type; $types .= "s"; }
if ($filter_priority !== 'all') { $where .= " AND priority = ?"; $params[] = $filter_priority; $types .= "s"; }
if ($search) { 
    $where .= " AND (name LIKE ? OR email LIKE ? OR phone LIKE ? OR subject LIKE ? OR message LIKE ?)";
    $like = "%$search%";
    $params = array_merge($params, [$like, $like, $like, $like, $like]);
    $types .= "sssss";
}

$stmt = mysqli_prepare($db, "SELECT * FROM contacts_sch $where ORDER BY FIELD(status,'new','read','replied','resolved','closed'), FIELD(priority,'urgent','high','medium','low'), id DESC LIMIT 100");
mysqli_stmt_bind_param($stmt, $types, ...$params);
mysqli_stmt_execute($stmt);
$contacts_result = mysqli_stmt_get_result($stmt);
$total_contacts = mysqli_num_rows($contacts_result);

// Stats
$stats_stmt = mysqli_prepare($db, "SELECT COUNT(*) as total, SUM(status='new') as new_count, SUM(status='replied') as replied, SUM(status='resolved') as resolved, SUM(enquiry_type='admission') as admissions, SUM(priority='urgent') as urgent FROM contacts_sch WHERE school_id=?");
mysqli_stmt_bind_param($stats_stmt, "i", $school_id);
mysqli_stmt_execute($stats_stmt);
$stats = mysqli_fetch_assoc(mysqli_stmt_get_result($stats_stmt));

// View single contact
$view_contact = null;
if ($_GET['view_id'] ?? false) {
    $view_id = (int)$_GET['view_id'];
    $view_stmt = mysqli_prepare($db, "SELECT * FROM contacts_sch WHERE id=? AND school_id=?");
    mysqli_stmt_bind_param($view_stmt, "ii", $view_id, $school_id);
    mysqli_stmt_execute($view_stmt);
    $view_result = mysqli_stmt_get_result($view_stmt);
    $view_contact = mysqli_fetch_assoc($view_result);
    
    if ($view_contact && $view_contact['status'] == 'new') {
        $mark_stmt = mysqli_prepare($db, "UPDATE contacts_sch SET status='read' WHERE id=?");
        mysqli_stmt_bind_param($mark_stmt, "i", $view_id);
        mysqli_stmt_execute($mark_stmt);
        $view_contact['status'] = 'read';
    }
}

// Delete (with confirmation via POST recommended, but keeping GET for now)
if ($_GET['delete_id'] ?? false) {
    $delete_id = (int)$_GET['delete_id'];
    $delete_stmt = mysqli_prepare($db, "DELETE FROM contacts_sch WHERE id=? AND school_id=?");
    mysqli_stmt_bind_param($delete_stmt, "ii", $delete_id, $school_id);
    if (mysqli_stmt_execute($delete_stmt)) {
        $messages[] = ['type' => 'success', 'text' => 'Contact deleted!'];
    }
    header("Location: contacts.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <style>
        /* Your existing CSS - paste your full CSS here */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #f5f6fa; color: #2c3e50; }
        /* ... rest of your CSS ... */
        .table-container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6; }
        th { background: #f8f9fa; font-weight: 600; }
        tr:hover { background: #f8f9fa; }
        .btn { padding: 6px 12px; border-radius: 6px; text-decoration: none; margin-right: 5px; font-size: 0.85em; }
        .btn-view { background: #17a2b8; color: white; }
        .btn-delete { background: #e74c3c; color: white; }
        .alert { padding: 15px; margin: 20px 0; border-radius: 8px; }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-error { background: #f8d7da; color: #721c24; }
        @media (max-width: 768px) { .table-container { overflow-x: auto; } }
    </style>
</head>
<body>
    <div class="main-container">
        <h1>📧 Contacts Management (<?php echo $total_contacts; ?>)</h1>
        
        <!-- Messages -->
        <?php foreach ($messages as $msg): ?>
            <div class="alert alert-<?php echo $msg['type']; ?>">
                <?php echo htmlspecialchars($msg['text']); ?>
            </div>
        <?php endforeach; ?>

        <?php if (!$view_contact): ?>
        <!-- CONTACTS TABLE -->
        <div class="table-container">
            <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>
                        <td>#<?php echo $contact['id']; ?></td>
                        <td><?php echo htmlspecialchars($contact['enquiry_type']); ?></td>
                        <td><?php echo htmlspecialchars($contact['name']); ?></td>
                        <td><?php echo htmlspecialchars($contact['email']); ?></td>
                        <td><?php echo htmlspecialchars($contact['subject']); ?></td>
                        <td><?php echo ucfirst($contact['priority']); ?></td>
                        <td><?php echo ucfirst($contact['status']); ?></td>
                        <td><?php echo date('d M Y', strtotime($contact['created_at'])); ?></td>
                        <td>
                            <a href="?view_id=<?php echo $contact['id']; ?>" class="btn btn-view">View</a>
                            <a href="?delete_id=<?php echo $contact['id']; ?>" class="btn btn-delete" onclick="return confirm('Delete?')">Delete</a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            <?php if ($total_contacts == 0): ?>
                <p style="text-align: center; padding: 40px; color: #7f8c8d;">No contacts found</p>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <!-- VIEW CONTACT -->
        <div class="contact-detail">
            <h2><?php echo htmlspecialchars($view_contact['subject']); ?></h2>
            <p><strong>Name:</strong> <?php echo htmlspecialchars($view_contact['name']); ?></p>
            <p><strong>Email:</strong> <?php echo htmlspecialchars($view_contact['email']); ?></p>
            <p><strong>Message:</strong> <?php echo nl2br(htmlspecialchars($view_contact['message'])); ?></p>
            <a href="contacts.php">← Back to List</a>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>
