<?php

namespace App\Controllers;

use App\Utils\Auth;
use App\Utils\Flash;
use App\Config\Database;
use App\Utils\ExpiryAlertHelper;
use App\Utils\ExpiryPDFGenerator;
use App\Utils\SimpleMailer;

class SettingsController {

    public function index() {
        Auth::requireAdmin();
        $user = Auth::user();
        
        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM tenants WHERE id = ?");
        $stmt->execute([$user['tenant_id']]);
        $tenant = $stmt->fetch();

        require_once __DIR__ . '/../../views/admin/settings.php';
    }

    public function update() {
        Auth::requireAdmin();
        $user = Auth::user();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header("Location: /settings");
            exit;
        }

        $name = $_POST['name'] ?? '';
        $contactPerson = $_POST['contact_person'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $address = $_POST['address'] ?? '';
        $country = $_POST['country'] ?? '';
        $currencyCode = $_POST['currency_code'] ?? '$';

        $alertEmails = $_POST['alert_emails'] ?? '';
        
        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM tenants WHERE id = ?");
        $stmt->execute([$user['tenant_id']]);
        $tenant = $stmt->fetch();
        
        $waNames = $_POST['whatsapp_name'] ?? [];
        $waPhones = $_POST['whatsapp_phone'] ?? [];
        $maxWa = $tenant['max_whatsapp_recipients'] ?? 1;
        $waAlerts = [];
        for ($i = 0; $i < count($waNames); $i++) {
            $n = trim($waNames[$i]);
            $p = trim($waPhones[$i]);
            if (!empty($n) || !empty($p)) {
                if (count($waAlerts) < $maxWa) {
                    $waAlerts[] = ['name' => $n, 'phone' => $p];
                }
            }
        }
        $whatsappAlertsJson = !empty($waAlerts) ? json_encode($waAlerts) : null;

        if (empty($name)) {
            Flash::set('error', 'Pharmacy name is required.');
            header("Location: /settings");
            exit;
        }
        
        $db = Database::getInstance()->getConnection();
        
        // Handle Logo Upload
        $logoPath = null;
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../../public/uploads/logos/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileInfo = pathinfo($_FILES['logo']['name']);
            $ext = strtolower($fileInfo['extension']);
            $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp'];
            
            if (in_array($ext, $allowedExts)) {
                $newFileName = 'logo_' . $user['tenant_id'] . '_' . time() . '.' . $ext;
                $destPath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $destPath)) {
                    $logoPath = '/uploads/logos/' . $newFileName;
                }
            } else {
                Flash::set('error', 'Invalid logo format. Allowed: JPG, PNG, GIF, SVG, WEBP.');
                header("Location: /settings");
                exit;
            }
        }

        if ($logoPath) {
            $stmt = $db->prepare("UPDATE tenants SET name = ?, contact_person = ?, phone = ?, address = ?, country = ?, currency_code = ?, alert_emails = ?, whatsapp_alerts = ?, logo_path = ? WHERE id = ?");
            $stmt->execute([$name, $contactPerson, $phone, $address, $country, $currencyCode, $alertEmails, $whatsappAlertsJson, $logoPath, $user['tenant_id']]);
            $_SESSION['tenant_logo'] = $logoPath;
        } else {
            $stmt = $db->prepare("UPDATE tenants SET name = ?, contact_person = ?, phone = ?, address = ?, country = ?, currency_code = ?, alert_emails = ?, whatsapp_alerts = ? WHERE id = ?");
            $stmt->execute([$name, $contactPerson, $phone, $address, $country, $currencyCode, $alertEmails, $whatsappAlertsJson, $user['tenant_id']]);
        }

        $_SESSION['currency_code'] = $currencyCode;
        $_SESSION['tenant_name'] = $name;

        Flash::set('success', 'Settings updated successfully.');
        header("Location: /settings");
        exit;
    }

    public function triggerExpiryAlert() {
        Auth::requireAdmin();
        $user = Auth::user();
        
        $db = Database::getInstance()->getConnection();
        
        // Fetch Tenant settings to get alert email addresses and tenant name
        $stmt = $db->prepare("SELECT * FROM tenants WHERE id = ?");
        $stmt->execute([$user['tenant_id']]);
        $tenant = $stmt->fetch();
        
        if (!$tenant) {
            Flash::set('error', 'Tenant not found.');
            header("Location: /settings");
            exit;
        }
        
        $alertEmails = trim($tenant['alert_emails'] ?? '');
        if (empty($alertEmails)) {
            // Log config failure
            $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'failure', 'Email addresses not configured', ?, 0)");
            $stmtLog->execute([$user['tenant_id'], $alertEmails]);

            Flash::set('error', 'Please configure the Expiry Alert Email Addresses first.');
            header("Location: /settings");
            exit;
        }
        
        // Fetch expiring items
        $items = ExpiryAlertHelper::getExpiringSoonItems($user['tenant_id']);
        $count = count($items);
        
        if ($count === 0) {
            // Log 0 items count
            $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'failure', 'No expiring soon items found based on the current date', ?, 0)");
            $stmtLog->execute([$user['tenant_id'], $alertEmails]);

            Flash::set('error', 'No expiring soon items found based on the current date.');
            header("Location: /settings");
            exit;
        }
        
        try {
            // Generate PDF Report
            $pdfGenerator = new ExpiryPDFGenerator($tenant['name']);
            $pdfContent = $pdfGenerator->generate($items);
            
            // Build Email content using application theme template
            $subject = "Expiry Alerts Notification - " . $tenant['name'];
            $year = date('Y');
            
            // HTML body matching application theme
            $htmlBody = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Expiry Alert Notification</title>
    <style>
        body {
            background-color: #0f172a !important;
            color: #f1f5f9 !important;
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: #1e293b !important;
            border: 1px solid #334155;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        .header {
            border-bottom: 2px solid #4f46e5;
            padding-bottom: 15px;
            margin-bottom: 20px;
            text-align: center;
        }
        .header h1 {
            color: #818cf8 !important;
            margin: 0;
            font-size: 24px;
        }
        .content {
            line-height: 1.6;
            font-size: 16px;
            color: #cbd5e1 !important;
        }
        .alert-box {
            background-color: rgba(239, 68, 68, 0.1) !important;
            border-left: 4px solid #ef4444;
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
        }
        .footer {
            margin-top: 30px;
            font-size: 12px;
            color: #94a3b8 !important;
            text-align: center;
            border-top: 1px solid #334155;
            padding-top: 15px;
        }
        p {
            color: #cbd5e1 !important;
        }
    </style>
</head>
<body style="background-color: #0f172a; color: #f1f5f9; font-family: 'Inter', sans-serif; margin: 0; padding: 20px;">
    <div class="container" style="background-color: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 30px; max-width: 600px; margin: 0 auto;">
        <div class="header" style="border-bottom: 2px solid #4f46e5; padding-bottom: 15px; margin-bottom: 20px; text-align: center;">
            <h1 style="color: #818cf8; margin: 0; font-size: 24px; font-family: 'Inter', sans-serif;">Expiry Alert Notification</h1>
        </div>
        <div class="content" style="font-family: 'Inter', sans-serif; font-size: 16px; line-height: 1.6; color: #cbd5e1;">
            <p style="color: #cbd5e1; margin-bottom: 16px;">Dear Administrator,</p>
            <p style="color: #cbd5e1; margin-bottom: 16px;">This is a system generated notification regarding expiring soon medicine inventory items.</p>
            <div class="alert-box" style="background-color: rgba(239, 68, 68, 0.1); border-left: 4px solid #ef4444; padding: 15px; border-radius: 6px; margin: 20px 0;">
                <p style="margin: 0; color: #fca5a5; font-weight: bold;">We found <strong>{$count}</strong> batch(es) that are expiring soon based on current alert settings.</p>
            </div>
            <p style="color: #cbd5e1; margin-bottom: 16px;">A detailed PDF report has been generated and attached to this email containing the list of medicine details, batch numbers, branches, quantities, and days remaining.</p>
            <p style="color: #cbd5e1; margin-bottom: 16px;">Please take necessary actions to manage or withdraw these items.</p>
        </div>
        <div class="footer" style="margin-top: 30px; font-size: 12px; color: #94a3b8; text-align: center; border-top: 1px solid #334155; padding-top: 15px; font-family: 'Inter', sans-serif;">
            <p style="margin: 0 0 5px; color: #94a3b8;">&copy; {$year} {$tenant['name']}. All rights reserved.</p>
            <p style="margin: 0; color: #94a3b8;">NexCore-Pharma System Alert</p>
        </div>
    </div>
</body>
</html>
HTML;

            $localTime = new \DateTime('now', new \DateTimeZone('Asia/Colombo'));
            $pdfFilename = "expiry_report_" . $localTime->format('Ymd_His') . ".pdf";
            
            // Send email
            SimpleMailer::send($alertEmails, $subject, $htmlBody, $pdfContent, $pdfFilename);
            
            // Log success
            $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, channel, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'Email', 'success', NULL, ?, ?)");
            $stmtLog->execute([$user['tenant_id'], $alertEmails, $count]);

            Flash::set('success', "Expiry notification triggered successfully! Sent to: {$alertEmails}. Found {$count} item(s).");
        } catch (\Exception $e) {
            // Log failure with reason
            $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, channel, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'Email', 'failure', ?, ?, ?)");
            $stmtLog->execute([$user['tenant_id'], $e->getMessage(), $alertEmails, $count]);

            Flash::set('error', "Failed to send alert: " . $e->getMessage());
        }
        
        header("Location: /settings");
        exit;
    }
    public function triggerWhatsAppAlert() {
        Auth::requireAdmin();
        $user = Auth::user();
        
        $db = Database::getInstance()->getConnection();
        
        $stmt = $db->prepare("SELECT * FROM tenants WHERE id = ?");
        $stmt->execute([$user['tenant_id']]);
        $tenant = $stmt->fetch();
        
        if (!$tenant) {
            Flash::set('error', 'Tenant not found.');
            header("Location: /settings");
            exit;
        }
        
        $waAlerts = !empty($tenant['whatsapp_alerts']) ? json_decode($tenant['whatsapp_alerts'], true) : [];
        if (empty($waAlerts)) {
            Flash::set('error', 'Please configure WhatsApp Alerts contacts first.');
            header("Location: /settings");
            exit;
        }
        
        $items = ExpiryAlertHelper::getExpiringSoonItems($user['tenant_id']);
        $count = count($items);
        
        if ($count === 0) {
            Flash::set('error', 'No expiring soon items found to send alerts for.');
            header("Location: /settings");
            exit;
        }
        
        try {
            $successCount = 0;
            $failCount = 0;
            $errors = [];
            $maxDays = max(array_column($items, 'days_left'));
            
            // Format days into user-friendly string
            $months = floor($maxDays / 30);
            $days = $maxDays % 30;
            
            $friendlyDuration = "";
            if ($months > 0) {
                $friendlyDuration .= $months . " month" . ($months > 1 ? "s" : "");
            }
            if ($days > 0) {
                if ($months > 0) $friendlyDuration .= ", ";
                $friendlyDuration .= $days . " day" . ($days > 1 ? "s" : "");
            }
            if (empty($friendlyDuration)) {
                $friendlyDuration = "0 days";
            }
            
            $stmtAppUrl = $db->query("SELECT setting_value FROM settings WHERE setting_key = 'application_url'");
            $appUrlSetting = $stmtAppUrl->fetchColumn();
            $appUrl = $appUrlSetting ? $appUrlSetting : ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? 'localhost:8000'));
            
            foreach ($waAlerts as $contact) {
                if (empty($contact['phone'])) continue;
                $phone = $contact['phone'];
                $contactName = $contact['name'] ?: 'Admin';
                
                $contentVariables = [
                    '1' => $contactName,
                    '2' => (string)$count,
                    '3' => $friendlyDuration,
                    '4' => $appUrl
                ];
                
                try {
                    \App\Utils\WhatsAppAlertHelper::sendTemplate($phone, $contentVariables);
                    $successCount++;
                } catch (\Exception $e) {
                    $failCount++;
                    $errors[] = "Failed for $phone: " . $e->getMessage();
                }
            }
            
            $waRecipientsStr = implode(',', array_column($waAlerts, 'phone'));
            
            if ($successCount > 0) {
                $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, channel, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'WhatsApp', 'success', NULL, ?, ?)");
                $stmtLog->execute([$user['tenant_id'], $waRecipientsStr, $count]);
                
                Flash::set('success', "WhatsApp notification triggered! Sent successfully to $successCount contact(s)." . ($failCount > 0 ? " ($failCount failed)" : ""));
            } else {
                $failureReason = implode(", ", $errors);
                $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, channel, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'WhatsApp', 'failure', ?, ?, ?)");
                $stmtLog->execute([$user['tenant_id'], $failureReason, $waRecipientsStr, $count]);
                
                Flash::set('error', "Failed to send WhatsApp alerts. " . $failureReason);
            }
        } catch (\Exception $e) {
            $stmtLog = $db->prepare("INSERT INTO notifyalertlog (tenant_id, alert_type, channel, status, failure_reason, recipients, items_count) VALUES (?, 'manual', 'WhatsApp', 'failure', ?, ?, ?)");
            $stmtLog->execute([$user['tenant_id'], $e->getMessage(), '', $count ?? 0]);
            
            Flash::set('error', "Failed to process WhatsApp alerts: " . $e->getMessage());
        }
        
        header("Location: /settings");
        exit;
    }
}
