<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Contact Controller
 *
 * Handles the contact form display and submission.
 * Sends instant email notification to admin on each enquiry.
 */
class ContactController extends Controller
{
    /**
     * Display the contact form.
     *
     * @return void
     */
    public function index(): void
    {
        $settingModel = $this->model('Setting');
        $settings = $settingModel->getAll();

        $this->view('contact/index', [
            'title'      => 'Contact Us - Gmind Institute',
            'settings'   => $settings,
            'currentNav' => 'contact',
        ]);
    }

    /**
     * Process the contact form submission.
     *
     * Validates CSRF token, sanitizes inputs, inserts a contact message
     * record, and sends an instant email notification to admin.
     *
     * @return void
     */
    public function store(): void
    {
        $this->validateCsrf();

        $name    = sanitize($_POST['name'] ?? '');
        $email   = sanitize($_POST['email'] ?? '');
        $phone   = sanitize($_POST['phone'] ?? '');
        $subject = sanitize($_POST['subject'] ?? '');
        $message = sanitize($_POST['message'] ?? '');

        // Basic validation
        if (empty($name) || empty($email) || empty($message)) {
            flash('error', 'Please fill in all required fields (Name, Email, and Message).');
            redirect(BASE_PATH . '/contact');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect(BASE_PATH . '/contact');
        }

        try {
            $contactModel = $this->model('Contact');
            $contactModel->create([
                'name'    => $name,
                'email'   => $email,
                'phone'   => $phone,
                'subject' => $subject,
                'message' => $message,
                'is_read' => 0,
            ]);

            flash('success', 'Your message has been sent successfully! We will get back to you soon.');

            // Send instant email notification to admin
            $this->sendAdminNotification($name, $email, $phone, $subject, $message);

            redirect(BASE_PATH . '/contact');
        } catch (\Throwable $e) {
            error_log('Contact form error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again later.');
            redirect(BASE_PATH . '/contact');
        }
    }

    /**
     * Send instant email notification to admin when a contact enquiry is submitted.
     *
     * @param string $name    Sender name
     * @param string $email   Sender email
     * @param string $phone   Sender phone
     * @param string $subject Message subject
     * @param string $message Message body
     */
    private function sendAdminNotification(string $name, string $email, string $phone, string $subject, string $message): void
    {
        $logFile = dirname(__DIR__, 2) . '/logs/email_debug.log';
        $logDir = dirname($logFile);
        if (!is_dir($logDir)) {
            @mkdir($logDir, 0755, true);
        }

        $log = function (string $msg) use ($logFile): void {
            $ts = date('Y-m-d H:i:s');
            @file_put_contents($logFile, "[{$ts}] CONTACT: {$msg}\n", FILE_APPEND);
            error_log('Contact email: ' . $msg);
        };

        try {
            $log('Starting email notification for contact from ' . $name);

            $adminEmail = 'gmindinstitues@gmail.com';
            $emailSubject = 'New Contact Enquiry - ' . $name;

            $htmlBody = '
            <div style="font-family: Arial, Helvetica, sans-serif; max-width: 600px; margin: 0 auto; background: #f4f7fc; padding: 20px;">
                <div style="background: #ffffff; border-radius: 12px; padding: 30px; box-shadow: 0 2px 12px rgba(0,0,0,0.08);">
                    <div style="text-align: center; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 3px solid #4A6CF7;">
                        <h1 style="margin: 0; color: #0d2b6e; font-size: 22px;">New Contact Enquiry</h1>
                        <p style="margin: 6px 0 0; color: #888; font-size: 13px;">Gmind Institute — ' . date('d M Y, h:i A') . '</p>
                    </div>

                    <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
                        <tr>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #666; font-weight: 600; width: 140px;">Name</td>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #333;">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #666; font-weight: 600;">Email</td>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #333;">
                                <a href="mailto:' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '" style="color: #4A6CF7;">' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '</a>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #666; font-weight: 600;">Phone</td>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #333;">
                                <a href="tel:' . htmlspecialchars($phone, ENT_QUOTES, 'UTF-8') . '" style="color: #4A6CF7;">' . htmlspecialchars($phone, ENT_QUOTES, 'UTF-8') . '</a>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #666; font-weight: 600;">Subject</td>
                            <td style="padding: 10px 12px; border-bottom: 1px solid #eee; color: #333;">' . htmlspecialchars($subject ?: 'N/A', ENT_QUOTES, 'UTF-8') . '</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px 12px; color: #666; font-weight: 600; vertical-align: top;">Message</td>
                            <td style="padding: 10px 12px; color: #333; line-height: 1.6;">' . nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8')) . '</td>
                        </tr>
                    </table>
                </div>
                <p style="text-align: center; color: #aaa; font-size: 11px; margin-top: 16px;">
                    This is an automated notification from Gmind Institute website.
                </p>
            </div>';

            $textBody = "New Contact Enquiry\n"
                      . "========================\n"
                      . "Name: {$name}\n"
                      . "Email: {$email}\n"
                      . "Phone: {$phone}\n"
                      . "Subject: " . ($subject ?: 'N/A') . "\n"
                      . "Message: {$message}\n"
                      . "Time: " . date('d M Y, h:i A');

            // Strategy 1: Use App\Core\Mail
            try {
                $mail = new \App\Core\Mail();

                if ($mail->isAvailable() && $mail->isConfigured()) {
                    $sent = $mail->send($adminEmail, 'Gmind Admin', $emailSubject, $htmlBody, $textBody);
                    if ($sent) {
                        $log('SUCCESS: Notification sent via App\Core\Mail');
                        return;
                    }
                    $log('Strategy 1 FAILED: ' . $mail->getLastError());
                } else {
                    $log('Strategy 1 SKIP: Mail not available/configured');
                }
            } catch (\Throwable $e) {
                $log('Strategy 1 EXCEPTION: ' . $e->getMessage());
            }

            // Strategy 2: Direct PHPMailer
            try {
                $phpMailerPath = null;
                $searchPaths = [
                    dirname(__DIR__, 2) . '/phpmailer/src',
                    rtrim($_SERVER['DOCUMENT_ROOT'] ?? '', '/') . (defined('BASE_PATH') ? BASE_PATH : '') . '/phpmailer/src',
                    rtrim($_SERVER['DOCUMENT_ROOT'] ?? '', '/') . '/phpmailer/src',
                ];
                foreach ($searchPaths as $p) {
                    $rp = realpath($p);
                    if ($rp && file_exists($rp . '/PHPMailer.php')) {
                        $phpMailerPath = $rp;
                        break;
                    }
                }

                if ($phpMailerPath) {
                    require_once $phpMailerPath . '/PHPMailer.php';
                    require_once $phpMailerPath . '/SMTP.php';
                    require_once $phpMailerPath . '/Exception.php';

                    // Read SMTP settings from DB
                    $smtpKeys = ['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'smtp_encryption', 'smtp_from_email', 'smtp_from_name'];
                    $smtp = [];
                    // Try setting_key/setting_value
                    $ph = implode(',', array_fill(0, count($smtpKeys), '?'));
                    $stmt = $this->db->prepare("SELECT `setting_key`, `setting_value` FROM `settings` WHERE `setting_key` IN ({$ph})");
                    $stmt->execute($smtpKeys);
                    foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
                        if (in_array($row['setting_key'] ?? '', $smtpKeys, true)) {
                            $smtp[$row['setting_key']] = $row['setting_value'] ?? '';
                        }
                    }
                    // Try key_name/value
                    $stmt = $this->db->prepare("SELECT `key_name`, `value` FROM `settings` WHERE `key_name` IN ({$ph})");
                    $stmt->execute($smtpKeys);
                    foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
                        $k = $row['key_name'] ?? '';
                        if (in_array($k, $smtpKeys, true) && (empty($smtp[$k]))) {
                            $smtp[$k] = $row['value'] ?? '';
                        }
                    }

                    if (!empty($smtp['smtp_host']) && !empty($smtp['smtp_from_email'])) {
                        $phpMail = new \PHPMailer\PHPMailer\PHPMailer(true);
                        $phpMail->isSMTP();
                        $phpMail->Host     = $smtp['smtp_host'];
                        $phpMail->Port     = (int) ($smtp['smtp_port'] ?? 465);
                        $phpMail->SMTPAuth = !empty($smtp['smtp_username']);
                        $phpMail->Username = $smtp['smtp_username'] ?? '';
                        $phpMail->Password = $smtp['smtp_password'] ?? '';
                        $phpMail->SMTPSecure = ($smtp['smtp_encryption'] ?? 'ssl') === 'ssl'
                            ? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS
                            : \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                        $phpMail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]];
                        $phpMail->CharSet = 'UTF-8';
                        $phpMail->Timeout = 30;
                        $phpMail->setFrom($smtp['smtp_from_email'], $smtp['smtp_from_name'] ?? 'Gmind Institute');
                        $phpMail->addAddress($adminEmail, 'Gmind Admin');
                        $phpMail->isHTML(true);
                        $phpMail->Subject = $emailSubject;
                        $phpMail->Body = $htmlBody;
                        $phpMail->AltBody = $textBody;
                        $phpMail->send();
                        $log('SUCCESS: Notification sent via direct PHPMailer');
                        return;
                    }
                    $log('Strategy 2 SKIP: SMTP not configured');
                } else {
                    $log('Strategy 2 SKIP: PHPMailer not found');
                }
            } catch (\Throwable $e) {
                $log('Strategy 2 EXCEPTION: ' . $e->getMessage());
            }

            // Strategy 3: PHP mail() fallback
            try {
                $headers  = "From: Gmind Institute <noreply@gmind.in>\r\n";
                $headers .= "Reply-To: " . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . "\r\n";
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
                $mailResult = mail($adminEmail, $emailSubject, $htmlBody, $headers);
                if ($mailResult) {
                    $log('SUCCESS: Notification sent via PHP mail()');
                } else {
                    $log('Strategy 3 FAILED: PHP mail() returned false');
                }
            } catch (\Throwable $e) {
                $log('Strategy 3 EXCEPTION: ' . $e->getMessage());
            }

        } catch (\Throwable $e) {
            if (isset($log)) {
                $log('OUTER EXCEPTION: ' . $e->getMessage());
            }
        }
    }
}
