Path : /home/vishqocm/pcib.in/
File Upload :
Current File : //home/vishqocm/pcib.in/send_contact_email.php

<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'C:/xampp/logs/php_error.log');
error_reporting(E_ALL);

// Set headers for JSON response
header('Content-Type: application/json');

// Include PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Include database configuration if you want to save messages
require_once 'admin/database/db_config.php';

// Function to sanitize input data
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Initialize variables
$errors = [];
$name = $email = $subject = $message = $phone = '';

// Validate and sanitize inputs
if (empty($_POST['name'])) {
    $errors[] = 'Name is required';
} else {
    $name = sanitize_input($_POST['name']);
    if (strlen($name) < 2) {
        $errors[] = 'Name must be at least 2 characters';
    }
}

if (empty($_POST['email'])) {
    $errors[] = 'Email is required';
} else {
    $email = sanitize_input($_POST['email']);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format';
    }
}

if (empty($_POST['subject'])) {
    $errors[] = 'Subject is required';
} else {
    $subject = sanitize_input($_POST['subject']);
}

if (empty($_POST['message'])) {
    $errors[] = 'Message is required';
} else {
    $message = sanitize_input($_POST['message']);
    if (strlen($message) < 10) {
        $errors[] = 'Message must be at least 10 characters';
    }
}

// Phone is optional
if (!empty($_POST['phone'])) {
    $phone = sanitize_input($_POST['phone']);
}

// If there are validation errors, return them
if (!empty($errors)) {
    echo json_encode(['success' => false, 'message' => 'Please fix the following errors', 'errors' => $errors]);
    exit;
}

// Save to database - create table if it doesn't exist
try {
    // Check if table exists, if not create it
    $table_check = $conn->query("SHOW TABLES LIKE 'contact_messages'");
    if ($table_check->num_rows == 0) {
        $create_table = "CREATE TABLE contact_messages (
            id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(100) NOT NULL,
            subject VARCHAR(200) NOT NULL,
            message TEXT NOT NULL,
            phone VARCHAR(20) DEFAULT NULL,
            status ENUM('new', 'read', 'replied') DEFAULT 'new',
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NULL
        )";
        $conn->query($create_table);
    }
    
    // Insert message into database
    $stmt = $conn->prepare("INSERT INTO contact_messages (name, email, subject, message, phone, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("sssss", $name, $email, $subject, $message, $phone);
    $stmt->execute();
    $stmt->close();
    
} catch (Exception $e) {
    error_log("Database error: " . $e->getMessage());
    // Continue even if database fails - we'll still try to send the email
}

// Try to send the email
try {
    // Check if PHPMailer is installed
    if (!file_exists('vendor/autoload.php')) {
        // Create composer.json if it doesn't exist
        if (!file_exists('composer.json')) {
            file_put_contents('composer.json', json_encode([
                "require" => [
                    "phpmailer/phpmailer" => "^6.8"
                ]
            ], JSON_PRETTY_PRINT));
        }
        
        echo json_encode([
            'success' => false, 
            'message' => 'PHPMailer is not installed. Please run "composer require phpmailer/phpmailer" in your project root.'
        ]);
        exit;
    }
    
    // Include Composer's autoloader
    require 'vendor/autoload.php';
    
    // Create a new PHPMailer instance
    $mail = new PHPMailer(true);
    
    // Debug mode (set to 0 in production)
    $mail->SMTPDebug = 0;  // 0 = no output, 1 = client output, 2 = client and server output
    
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';  // Gmail SMTP server
    $mail->SMTPAuth   = true;
    $mail->Username   = '[email protected]'; // REPLACE WITH YOUR GMAIL ADDRESS
    $mail->Password   = 'xxxx xxxx xxxx xxxx'; // REPLACE WITH YOUR APP PASSWORD
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;
    
    // Recipients
    $mail->setFrom('[email protected]', 'Popular Computer Institute');
    $mail->addAddress('[email protected]', 'Popular Computer'); // Add a recipient
    $mail->addReplyTo($email, $name);
    
    // Content
    $mail->isHTML(true);
    $mail->Subject = 'New Contact Form Message: ' . $subject;
    
    // Email body
    $mail->Body = '
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            h2 { color: #4e73df; border-bottom: 1px solid #eee; padding-bottom: 10px; }
            .message-details { background-color: #f9f9f9; padding: 15px; border-radius: 5px; }
            .label { font-weight: bold; margin-right: 5px; }
        </style>
    </head>
    <body>
        <div class="container">
            <h2>New Contact Form Submission</h2>
            <div class="message-details">
                <p><span class="label">Name:</span> ' . htmlspecialchars($name) . '</p>
                <p><span class="label">Email:</span> ' . htmlspecialchars($email) . '</p>
                ' . (!empty($phone) ? '<p><span class="label">Phone:</span> ' . htmlspecialchars($phone) . '</p>' : '') . '
                <p><span class="label">Subject:</span> ' . htmlspecialchars($subject) . '</p>
                <p><span class="label">Message:</span></p>
                <p>' . nl2br(htmlspecialchars($message)) . '</p>
            </div>
        </div>
    </body>
    </html>';
    
    // Plain text version for non-HTML mail clients
    $mail->AltBody = "Name: $name\nEmail: $email\n" . (!empty($phone) ? "Phone: $phone\n" : "") . "Subject: $subject\n\nMessage:\n$message";
    
    // Send the email
    $mail->send();
    
    // Return success response
    echo json_encode(['success' => true, 'message' => 'Your message has been sent. We will get back to you soon!']);
    
} catch (Exception $e) {
    error_log("Email error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'There was an error sending your message. Please try again later.']);
}
?>