<?php

// Email configuration - USE YOUR OFFICIAL DOMAIN
$to_email = 'mohsinbashirraja@dsisajk.net, wajidmuzaffar@dsisajk.net, amirhamzakhan@dsisajk.net, shirazahmad@dsisajk.net, kabirahmed@dsisajk.net';
$from_email = 'noreply@dsisajk.net'; // MUST be your domain email
$subject = 'New Contact Us Form Submission From DSISAJK';

date_default_timezone_set('Asia/Karachi');

// Connect to database
include_once 'connect.php';

// Process form data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Input sanitization
    $name = htmlspecialchars(trim($_POST['name']));
    $contact = htmlspecialchars(trim($_POST['contact']));
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $message = htmlspecialchars(trim($_POST['message']));
    $submission_date = date('Y-m-d H:i:s');
    $client_ip = $_SERVER['REMOTE_ADDR'];

    // Validate inputs
    $errors = [];
    if (empty($name)) $errors[] = "Name is required";
    if (empty($contact)) $errors[] = "Contact number is required";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";
    if (empty($message)) $errors[] = "Message is required";
    
    if (!empty($errors)) {
        header("Location: contact_us.php?status=error&message=" . urlencode(implode(', ', $errors)));
        exit();
    }

    // Check submission limit
    $check_query = "SELECT COUNT(*) as count FROM contact_us 
                   WHERE ip_address = ? 
                   AND submission_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
    $stmt = $conn->prepare($check_query);
    $stmt->bind_param("s", $client_ip);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if ($row['count'] >= 2) {
        header("Location: contact_us.php?status=limit_exceeded");
        exit();
    }

    // Insert into database
    $insert_query = "INSERT INTO contact_us 
                    (name, contact_no, email, message, submission_date, ip_address) 
                    VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($insert_query);
    $stmt->bind_param("ssssss", $name, $contact, $email, $message, $submission_date, $client_ip);
    
    if (!$stmt->execute()) {
        header("Location: contact_us.php?status=db_error");
        exit();
    }

    // Improved Email Functionality
    $email_message = "
    <html>
    <head>
        <title>New Contact US Form Submission From DSISAJK</title>
                <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            h2 { color: #002147; border-bottom: 2px solid #c5a059; padding-bottom: 10px; }
            p { margin: 8px 0; }
            strong { color: #002147; }
            .subject-badge { 
                background: #c5a059; 
                color: #002147; 
                padding: 3px 10px; 
                border-radius: 4px; 
                font-weight: bold;
                display: inline-block;
            }
        </style>
    </head>
    <body>
        <h2>New Contact Us Form Submission From DSISAJK</h2>
        <p><strong>Name:</strong> $name</p>
        <p><strong>Contact No:</strong> $contact</p>
        <p><strong>Email:</strong> $email</p>
        <p><strong>Message:</strong><br>".nl2br($message)."</p>
        <p><strong>Submitted on:</strong> $submission_date</p>
        <p><strong>IP Address:</strong> $client_ip</p>
    </body>
    </html>
    ";

    // Set advanced headers
    $headers = "From: $from_email\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    $headers .= "X-Priority: 1 (Highest)\r\n";
    $headers .= "X-MSMail-Priority: High\r\n";

    // Send email with additional parameters
    $mail_sent = mail(
        $to_email, 
        $subject, 
        $email_message, 
        $headers,
        "-f $from_email" // Important for SPF validation
    );

    if ($mail_sent) {
        header("Location: contact_us.php?status=success");
    } else {
        // Enhanced error logging
        error_log("Email failed to send. Details:\n"
                 ."To: $to_email\n"
                 ."From: $from_email\n"
                 ."Subject: $subject\n"
                 ."Headers: $headers\n");
        header("Location: contact_us.php?status=mail_error");
    }
    
    $conn->close();
    exit();
} else {
    header("Location: contact_us.php");
    exit();
}
?>