<?php
class UserController {
    private $conn;
    private $userId;

    public function __construct($db) {
        $this->conn = $db;
        $this->userId = $_SESSION['user_id'] ?? 0;
    }

    public function dashboard() {
        // Stats
        $totalContacts = 0;
        $todaysBirthdays = 0;

        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM contacts WHERE user_id = ?");
        $stmt->bind_param("i", $this->userId);
        $stmt->execute();
        $totalContacts = $stmt->get_result()->fetch_assoc()['count'];

        $today = date('m-d');
        // MySQL DATE_FORMAT(dob, '%m-%d')
        $stmt2 = $this->conn->prepare("SELECT COUNT(*) as count FROM contacts WHERE user_id = ? AND DATE_FORMAT(dob, '%m-%d') = ?");
        $stmt2->bind_param("is", $this->userId, $today);
        $stmt2->execute();
        $todaysBirthdays = $stmt2->get_result()->fetch_assoc()['count'];

        require_once 'views/user/dashboard.php';
    }

    public function contacts() {
        $stmt = $this->conn->prepare("SELECT * FROM contacts WHERE user_id = ? ORDER BY name ASC");
        $stmt->bind_param("i", $this->userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $contacts = $result->fetch_all(MYSQLI_ASSOC);
        require_once 'views/user/contacts.php';
    }

    public function addContact() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = trim($_POST['name']);
            $mobile = trim($_POST['mobile']);
            $dob = $_POST['dob']; // YYYY-MM-DD

            if (!empty($name) && !empty($mobile) && !empty($dob)) {
                try {
                    $stmt = $this->conn->prepare("INSERT INTO contacts (user_id, name, mobile, dob) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("isss", $this->userId, $name, $mobile, $dob);
                    $stmt->execute();
                    setFlash('success', 'Contact added successfully.');
                } catch (mysqli_sql_exception $e) {
                    if ($e->getCode() == 1062) { // Duplicate entry
                        setFlash('error', 'Contact with this mobile number already exists.');
                    } else {
                        setFlash('error', 'Error adding contact: ' . $e->getMessage());
                    }
                }
            } else {
                setFlash('error', 'All fields are required.');
            }
        }
        header("Location: " . BASE_URL . "?page=user&action=contacts");
    }

    public function importContacts() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
            $file = $_FILES['csv_file']['tmp_name'];

            if (($handle = fopen($file, "r")) !== FALSE) {
                // Skip header row if it exists? Let's assume user provides header or we check first row.
                // Or just simple: Name, Mobile, DOB
                $csvData = [];
                $row = 0;
                $successCount = 0;
                $failCount = 0;

                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    // Check if it's likely a header
                    if ($row == 0 && (strtolower($data[0]) == 'name' || strtolower($data[0]) == 'contact name')) {
                        $row++;
                        continue;
                    }

                    if (count($data) >= 3) {
                        $name = trim($data[0]);
                        $mobile = trim($data[1]);
                        $dob = trim($data[2]); // Expecting YYYY-MM-DD

                        // Basic validation
                        if (!empty($name) && !empty($mobile) && !empty($dob)) {
                            // Try insert
                            try {
                                $stmt = $this->conn->prepare("INSERT INTO contacts (user_id, name, mobile, dob) VALUES (?, ?, ?, ?)");
                                $stmt->bind_param("isss", $this->userId, $name, $mobile, $dob);
                                $stmt->execute();
                                $successCount++;
                            } catch (Exception $e) {
                                $failCount++; // Likely duplicate
                            }
                        }
                    }
                    $row++;
                }
                fclose($handle);
                setFlash('success', "Import complete. Imported: $successCount. Skipped/Failed: $failCount.");
            } else {
                setFlash('error', 'Invalid file.');
            }
        }
        header("Location: " . BASE_URL . "?page=user&action=contacts");
    }

    public function deleteContact() {
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $stmt = $this->conn->prepare("DELETE FROM contacts WHERE id = ? AND user_id = ?");
            $stmt->bind_param("ii", $id, $this->userId);
            $stmt->execute();
            setFlash('success', 'Contact deleted.');
        }
        header("Location: " . BASE_URL . "?page=user&action=contacts");
    }

    public function template() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['template_image'])) {
            $target_dir = "uploads/templates/";
            $file_name = time() . '_' . basename($_FILES["template_image"]["name"]);
            $target_file = $target_dir . $file_name;

            $check = getimagesize($_FILES["template_image"]["tmp_name"]);
            if($check !== false) {
                 if (move_uploaded_file($_FILES["template_image"]["tmp_name"], $target_file)) {
                     // Update DB
                     $stmt = $this->conn->prepare("UPDATE user_templates SET image_path = ? WHERE user_id = ?");
                     $stmt->bind_param("si", $target_file, $this->userId);
                     $stmt->execute();

                     // If no rows updated, insert new (though registration ensures one exists)
                     if ($stmt->affected_rows == 0) {
                         // Double check if row exists
                         // ... Assuming it exists from register. But if not:
                         // INSERT
                     }
                     setFlash('success', 'Template updated successfully.');
                 } else {
                     setFlash('error', 'Error uploading file.');
                 }
            } else {
                setFlash('error', 'File is not an image.');
            }
        }

        // Fetch current template
        $stmt = $this->conn->prepare("SELECT image_path FROM user_templates WHERE user_id = ?");
        $stmt->bind_param("i", $this->userId);
        $stmt->execute();
        $tpl = $stmt->get_result()->fetch_assoc();
        $currentTemplate = $tpl ? $tpl['image_path'] : '';

        require_once 'views/user/template.php';
    }

    public function birthdays() {
        $today = date('m-d');
        $stmt = $this->conn->prepare("SELECT * FROM contacts WHERE user_id = ? AND DATE_FORMAT(dob, '%m-%d') = ?");
        $stmt->bind_param("is", $this->userId, $today);
        $stmt->execute();
        $birthdays = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        require_once 'views/user/birthdays.php';
    }

    public function sendWishes() {
        require_once 'services/MessageService.php';
        $msgService = new MessageService($this->conn);

        // 1. Get Today's Birthdays
        $today = date('m-d');
        $stmt = $this->conn->prepare("SELECT * FROM contacts WHERE user_id = ? AND DATE_FORMAT(dob, '%m-%d') = ?");
        $stmt->bind_param("is", $this->userId, $today);
        $stmt->execute();
        $birthdays = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        // 2. Get User API & Template
        $stmtApi = $this->conn->prepare("SELECT * FROM user_apis WHERE user_id = ?");
        $stmtApi->bind_param("i", $this->userId);
        $stmtApi->execute();
        $apiData = $stmtApi->get_result()->fetch_assoc();

        // 3. Get Template & Greeting
        $stmtTpl = $this->conn->prepare("SELECT image_path, greeting_text, pos_x, pos_y, font_size, font_color FROM user_templates WHERE user_id = ?");
        $stmtTpl->bind_param("i", $this->userId);
        $stmtTpl->execute();
        $tplData = $stmtTpl->get_result()->fetch_assoc();

        if (!$birthdays) {
            setFlash('error', 'No birthdays today to send.');
            header("Location: " . BASE_URL . "?page=user&action=birthdays");
            exit;
        }

        if (!$tplData || !file_exists($tplData['image_path'])) {
            setFlash('error', 'No template found. Please upload one.');
            header("Location: " . BASE_URL . "?page=user&action=template");
            exit;
        }

        // Prepare API Data bundle
        $apiConfig = [
            'wa_url'         => $apiData['wa_url'],
            'wa_apikey'      => $apiData['wa_apikey'],
            'sms_url'        => $apiData['sms_api_url'],
            'sms_user'       => $apiData['sms_user'],
            'sms_password'   => $apiData['sms_password'],
            'sms_sender_id'  => $apiData['sms_sender_id']
        ];

        // Determine which channel to use: 'whatsapp' or 'sms'
        $messageType = isset($_POST['message_type']) ? trim($_POST['message_type']) : 'whatsapp';
        if (!in_array($messageType, ['whatsapp', 'sms'])) {
            $messageType = 'whatsapp';
        }

        $sentCount = 0;
        foreach ($birthdays as $bday) {
            // Personalize Message
            $greeting = isset($tplData['greeting_text']) ? $tplData['greeting_text'] : "Happy Birthday {NAME}!";
            $personalizedMsg = !empty($greeting)
                ? str_replace('{NAME}', $bday['name'], $greeting)
                : "Happy Birthday " . $bday['name'];

            $apiConfig['message'] = $personalizedMsg;

            // Generate PDF
            $pdfName = 'birthday_' . $this->userId . '_' . $bday['id'] . '_' . time() . '.pdf';
            $pdfPath = 'uploads/temp_pdfs/' . $pdfName;

            $tplOptions = [
                'pos_x'      => $tplData['pos_x']      ?? 50,
                'pos_y'      => $tplData['pos_y']      ?? 90,
                'font_size'  => $tplData['font_size']  ?? 20,
                'font_color' => $tplData['font_color'] ?? '#000000'
            ];

            try {
                $msgService->generateBirthdayPdf($tplData['image_path'], $bday['name'], $pdfPath, $tplOptions);

                if ($messageType === 'whatsapp') {
                    // ── Send WhatsApp ONLY ────────────────────────────────
                    $waResp    = $msgService->sendWhatsApp($apiConfig, $bday['mobile'], $pdfPath);
                    $statusWa  = $waResp['status'] == 'success' ? 'success' : 'failed';
                    $respTextWa = "WA: " . json_encode($waResp);

                    $stmtLog = $this->conn->prepare(
                        "INSERT INTO message_logs (user_id, contact_id, message_type, status, response_text) VALUES (?, ?, 'whatsapp', ?, ?)"
                    );
                    $stmtLog->bind_param("iiss", $this->userId, $bday['id'], $statusWa, $respTextWa);
                    $stmtLog->execute();

                    if ($statusWa == 'success') $sentCount++;

                } elseif ($messageType === 'sms') {
                    // ── Send Text SMS ONLY ────────────────────────────────
                    $smsResp    = $msgService->sendSMS($apiConfig, $bday['mobile'], $personalizedMsg);
                    $statusSms  = $smsResp['status'] == 'success' ? 'success' : 'failed';
                    $respTextSms = "SMS: " . json_encode($smsResp);

                    $stmtLog2 = $this->conn->prepare(
                        "INSERT INTO message_logs (user_id, contact_id, message_type, status, response_text) VALUES (?, ?, 'sms', ?, ?)"
                    );
                    $stmtLog2->bind_param("iiss", $this->userId, $bday['id'], $statusSms, $respTextSms);
                    $stmtLog2->execute();

                    if ($statusSms == 'success') $sentCount++;
                }

            } catch (Exception $e) {
                // Log error silently
            }
        }

        $channelLabel = $messageType === 'whatsapp' ? 'WhatsApp' : 'Text SMS';
        setFlash('success', "Processed $sentCount contacts via $channelLabel.");
        header("Location: " . BASE_URL . "?page=user&action=birthdays");
    }
}
