<?php
class Subscription {
    private $db;
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    // Get user subscription
    public function getUserSubscription($userId) {
        return $this->db->selectOne(
            "SELECT * FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
            [$userId]
        );
    }
    
    // Check if subscription is active
    public function isActive($userId) {
        $subscription = $this->getUserSubscription($userId);
        
        if (!$subscription) {
            return false;
        }
        
        if ($subscription['status'] === SUB_TRIAL) {
            if (strtotime($subscription['trial_ends_at']) > time()) {
                return true;
            }
        }
        
        if ($subscription['status'] === SUB_ACTIVE) {
            if ($subscription['end_date'] === null || strtotime($subscription['end_date']) > time()) {
                return true;
            }
        }
        
        return false;
    }
    
    // Create payment invoice for subscription renewal
    public function createPaymentInvoice($subscription_id, $user_id, $amount) {
        try {
            $invoiceNumber = 'INV-' . date('YmdHis') . '-' . rand(1000, 9999);
            $dueDate = date(DATE_FORMAT, strtotime('+7 days'));
            
            $paymentId = $this->db->insert('payments', [
                'subscription_id' => $subscription_id,
                'user_id' => $user_id,
                'amount' => $amount,
                'status' => PAYMENT_PENDING,
                'due_date' => $dueDate,
                'invoice_number' => $invoiceNumber
            ]);
            
            return ['success' => true, 'payment_id' => $paymentId, 'invoice_number' => $invoiceNumber];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Upgrade subscription plan
    public function upgradeSubscription($userId, $planType) {
        try {
            $subscription = $this->getUserSubscription($userId);

            if (!$subscription) {
                return ['success' => false, 'message' => 'Langganan tidak ditemukan'];
            }

            $amount = ($planType === 'yearly') ? SUBSCRIPTION_YEARLY : SUBSCRIPTION_MONTHLY;

            // Only update plan type & amount — activation happens after admin approves payment
            $this->db->update('subscriptions', [
                'plan_type' => $planType,
                'amount'    => $amount,
            ], ['id' => $subscription['id']]);

            return $this->createPaymentInvoice($subscription['id'], $userId, $amount);
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    // Submit payment proof (user action)
    public function submitPaymentProof($paymentId, $proofPath) {
        try {
            $this->db->update('payments', [
                'payment_proof' => $proofPath,
                'status'        => PAYMENT_REVIEWING,
            ], ['id' => $paymentId]);
            return ['success' => true];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    // Approve payment (admin action)
    public function approvePayment($paymentId) {
        try {
            $payment = $this->db->selectOne("SELECT * FROM payments WHERE id = ?", [$paymentId]);
            if (!$payment) {
                return ['success' => false, 'message' => 'Pembayaran tidak ditemukan'];
            }

            $this->db->update('payments', [
                'status'    => PAYMENT_PAID,
                'paid_date' => date(DATETIME_FORMAT),
            ], ['id' => $paymentId]);

            $subscription = $this->db->selectOne(
                "SELECT * FROM subscriptions WHERE id = ?",
                [$payment['subscription_id']]
            );
            $period  = $subscription['plan_type'] === 'yearly' ? '1 year' : '1 month';
            $endDate = date(DATE_FORMAT, strtotime('+' . $period));

            $this->db->update('subscriptions', [
                'status'       => SUB_ACTIVE,
                'end_date'     => $endDate,
                'is_trial'     => 0,
                'trial_ends_at'=> null,
            ], ['id' => $subscription['id']]);

            return ['success' => true];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    // Reject payment (admin action)
    public function rejectPayment($paymentId) {
        try {
            $this->db->update('payments', [
                'status' => PAYMENT_FAILED,
            ], ['id' => $paymentId]);
            return ['success' => true];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    // Get all payments for admin
    public function getAllPaymentsAdmin($status = null) {
        $sql = "SELECT p.*, u.name AS user_name, u.email AS user_email, s.plan_type
                FROM payments p
                JOIN users u ON p.user_id = u.id
                JOIN subscriptions s ON p.subscription_id = s.id";
        $params = [];
        if ($status) {
            $sql .= " WHERE p.status = ?";
            $params[] = $status;
        }
        $sql .= " ORDER BY p.created_at DESC";
        return $this->db->select($sql, $params);
    }
    
    // Process payment
    public function processPayment($paymentId, $status = PAYMENT_PAID) {
        try {
            $payment = $this->db->selectOne(
                "SELECT * FROM payments WHERE id = ?",
                [$paymentId]
            );
            
            if (!$payment) {
                return ['success' => false, 'message' => 'Pembayaran tidak ditemukan'];
            }
            
            if ($status === PAYMENT_PAID) {
                $this->db->update('payments', [
                    'status' => PAYMENT_PAID,
                    'paid_date' => date(DATETIME_FORMAT)
                ], ['id' => $paymentId]);
                
                // Update subscription
                $subscription = $this->getUserSubscription($payment['user_id']);
                $this->db->update('subscriptions', [
                    'status' => SUB_ACTIVE
                ], ['id' => $subscription['id']]);
                
                return ['success' => true, 'message' => 'Pembayaran berhasil diproses'];
            } else {
                $this->db->update('payments', [
                    'status' => $status
                ], ['id' => $paymentId]);
                
                return ['success' => true, 'message' => 'Status pembayaran diperbarui'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Get all payments by user
    public function getUserPayments($userId, $limit = 10, $offset = 0) {
        $limit = intval($limit);
        $offset = intval($offset);
        return $this->db->select(
            "SELECT * FROM payments WHERE user_id = ? ORDER BY created_at DESC LIMIT $limit OFFSET $offset",
            [$userId]
        );
    }
    
    // Get payment details
    public function getPaymentDetails($paymentId) {
        return $this->db->selectOne(
            "SELECT p.*, s.plan_type, s.status as sub_status FROM payments p 
             LEFT JOIN subscriptions s ON p.subscription_id = s.id 
             WHERE p.id = ?",
            [$paymentId]
        );
    }
    
    // Get subscription stats
    public function getSubscriptionStats($userId) {
        $subscription = $this->getUserSubscription($userId);
        $payments = $this->db->select(
            "SELECT COUNT(*) as total, SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as paid 
             FROM payments WHERE user_id = ?",
            [PAYMENT_PAID, $userId]
        );
        
        return [
            'subscription' => $subscription,
            'payments' => $payments[0] ?? ['total' => 0, 'paid' => 0],
            'is_active' => $this->isActive($userId),
            'days_remaining' => $this->getDaysRemaining($userId)
        ];
    }
    
    // Get days remaining
    public function getDaysRemaining($userId) {
        $subscription = $this->getUserSubscription($userId);
        
        if (!$subscription) {
            return 0;
        }
        
        if ($subscription['status'] === SUB_TRIAL) {
            $remaining = ceil((strtotime($subscription['trial_ends_at']) - time()) / 86400);
            return max(0, $remaining);
        }
        
        if ($subscription['end_date']) {
            $remaining = ceil((strtotime($subscription['end_date']) - time()) / 86400);
            return max(0, $remaining);
        }
        
        return 0;
    }

    // Send welcome email when user registers
    public function sendWelcomeEmail($userEmail, $userName) {
        try {
            $subject = 'Selamat Datang di KasirMurah.biz.id - Trial 1 Hari Gratis!';

            $message = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; color: #333; }
                    .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; border-radius: 8px; }
                    .header { background: linear-gradient(135deg, #6C5CE7 0%, #9B59B6 100%); color: white; padding: 30px 20px; text-align: center; border-radius: 8px 8px 0 0; }
                    .content { background: white; padding: 30px; }
                    .feature-list { margin: 20px 0; }
                    .feature { padding: 10px 0; border-bottom: 1px solid #eee; }
                    .feature:last-child { border-bottom: none; }
                    .cta-button { display: inline-block; background: #6C5CE7; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; }
                    .footer { text-align: center; color: #999; font-size: 12px; margin-top: 20px; }
                    .trial-badge { background: #FFF9ED; color: #C07300; padding: 10px; border-radius: 5px; margin: 20px 0; text-align: center; font-weight: bold; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h2>Selamat Datang, {$userName}! 🎉</h2>
                    </div>
                    <div class='content'>
                        <p>Terima kasih telah mendaftar di <strong>KasirMurah.biz.id</strong> - Aplikasi Kasir Online Mudah & Murah untuk UMKM.</p>

                        <div class='trial-badge'>
                            🎁 TRIAL GRATIS 1 HARI
                        </div>

                        <p>Akun Anda sudah aktif dan siap digunakan! Nikmati akses penuh ke semua fitur selama 1 hari percobaan gratis.</p>

                        <h3>Fitur yang Anda Dapatkan:</h3>
                        <div class='feature-list'>
                            <div class='feature'>✅ Sistem POS (Point of Sale) lengkap</div>
                            <div class='feature'>✅ Kelola produk unlimited</div>
                            <div class='feature'>✅ Catat semua transaksi penjualan</div>
                            <div class='feature'>✅ Laporan penjualan otomatis</div>
                            <div class='feature'>✅ Multi-user & multi-perangkat</div>
                            <div class='feature'>✅ Support 24/7</div>
                        </div>

                        <h3>Langkah Selanjutnya:</h3>
                        <ol>
                            <li>Login ke akun Anda</li>
                            <li>Tambahkan produk Anda</li>
                            <li>Mulai mencatat penjualan</li>
                            <li>Lihat laporan real-time</li>
                        </ol>

                        <p style='text-align: center;'>
                            <a href='" . APP_URL . "/dashboard.php' class='cta-button'>Mulai Sekarang</a>
                        </p>

                        <h3>Berlangganan Setelah Trial?</h3>
                        <p>Setelah 1 hari trial berakhir, Anda bisa berlangganan dengan paket:</p>
                        <ul>
                            <li><strong>Bulanan:</strong> Rp 50.000/bulan</li>
                            <li><strong>Tahunan:</strong> Rp 500.000/tahun (hemat 17%)</li>
                        </ul>

                        <p style='color: #999; font-size: 14px; margin-top: 20px;'>
                            Jika ada pertanyaan, jangan ragu untuk menghubungi kami di support@kasirmurah.biz.id
                        </p>

                        <div class='footer'>
                            <p>Email ini dikirim otomatis oleh sistem KasirMurah.biz.id</p>
                        </div>
                    </div>
                </div>
            </body>
            </html>
            ";

            $mail = new Mail();
            return $mail->send($userEmail, $subject, $message, true);
        } catch (Exception $e) {
            error_log("Welcome email failed: " . $e->getMessage());
            return false;
        }
    }

    // Send subscription expired notification email
    public function sendExpiredEmail($userEmail, $userName, $expiredDate) {
        try {
            $subject = 'Langganan Anda Telah Berakhir - KasirMurah.biz.id';

            $message = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; color: #333; }
                    .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; border-radius: 8px; }
                    .header { background: #E17055; color: white; padding: 30px 20px; text-align: center; border-radius: 8px 8px 0 0; }
                    .content { background: white; padding: 30px; }
                    .warning-box { background: #FFF0ED; border-left: 4px solid #E17055; padding: 15px; margin: 20px 0; border-radius: 5px; }
                    .cta-button { display: inline-block; background: #6C5CE7; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; }
                    .footer { text-align: center; color: #999; font-size: 12px; margin-top: 20px; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h2>⚠️ Langganan Berakhir</h2>
                    </div>
                    <div class='content'>
                        <p>Halo {$userName},</p>

                        <div class='warning-box'>
                            <strong>Langganan Anda telah berakhir pada {$expiredDate}</strong><br>
                            Sistem KasirMurah tidak dapat diakses sampai Anda memperpanjang langganan.
                        </div>

                        <h3>Apa yang Terjadi Sekarang?</h3>
                        <ul>
                            <li>❌ Anda tidak bisa mengakses sistem POS</li>
                            <li>❌ Anda tidak bisa menambah produk baru</li>
                            <li>❌ Anda tidak bisa mencatat transaksi</li>
                            <li>✅ Data Anda tetap aman dan tersimpan</li>
                        </ul>

                        <h3>Perpanjang Langganan Sekarang</h3>
                        <p>Perpanjang langganan Anda dan akses kembali semua fitur KasirMurah:</p>

                        <p style='text-align: center;'>
                            <a href='" . APP_URL . "/subscription/upgrade.php' class='cta-button'>Perpanjang Langganan</a>
                        </p>

                        <h3>Paket Langganan Kami:</h3>
                        <ul>
                            <li><strong>Bulanan:</strong> Rp 50.000/bulan</li>
                            <li><strong>Tahunan:</strong> Rp 500.000/tahun (hemat 17%)</li>
                        </ul>

                        <p style='color: #999; font-size: 14px; margin-top: 20px;'>
                            Pertanyaan? Hubungi kami di support@kasirmurah.biz.id
                        </p>

                        <div class='footer'>
                            <p>Email ini dikirim otomatis oleh sistem KasirMurah.biz.id</p>
                        </div>
                    </div>
                </div>
            </body>
            </html>
            ";

            $mail = new Mail();
            return $mail->send($userEmail, $subject, $message, true);
        } catch (Exception $e) {
            error_log("Expired email failed: " . $e->getMessage());
            return false;
        }
    }

    // Send payment notification email
    public function sendPaymentNotification($paymentId, $userEmail, $userName, $invoiceNumber, $amount) {
        try {
            $adminEmail = 'annuhliwan@gmail.com';
            $subject = 'Notifikasi Pembayaran Baru - KasirMurah.biz.id';

            $message = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; color: #333; }
                    .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; border-radius: 8px; }
                    .header { background: #6C5CE7; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                    .content { background: white; padding: 20px; }
                    .info-row { padding: 10px 0; border-bottom: 1px solid #eee; }
                    .info-row:last-child { border-bottom: none; }
                    .label { font-weight: bold; color: #6C5CE7; }
                    .amount { font-size: 24px; font-weight: bold; color: #00B894; }
                    .footer { text-align: center; color: #999; font-size: 12px; margin-top: 20px; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h2>Notifikasi Pembayaran Masuk</h2>
                    </div>
                    <div class='content'>
                        <p>Ada pembayaran baru yang perlu diverifikasi.</p>

                        <div class='info-row'>
                            <span class='label'>Nama User:</span> {$userName}
                        </div>
                        <div class='info-row'>
                            <span class='label'>Email:</span> {$userEmail}
                        </div>
                        <div class='info-row'>
                            <span class='label'>Nomor Invoice:</span> {$invoiceNumber}
                        </div>
                        <div class='info-row'>
                            <span class='label'>Jumlah Pembayaran:</span> <span class='amount'>Rp " . number_format($amount, 0, ',', '.') . "</span>
                        </div>
                        <div class='info-row'>
                            <span class='label'>Waktu Submit:</span> " . date('d M Y H:i:s') . "
                        </div>

                        <p style='margin-top: 20px;'>
                            <a href='" . APP_URL . "/admin/payments.php' style='background: #6C5CE7; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                                Verifikasi Pembayaran
                            </a>
                        </p>

                        <div class='footer'>
                            <p>Email ini dikirim otomatis oleh sistem KasirMurah.biz.id</p>
                        </div>
                    </div>
                </div>
            </body>
            </html>
            ";

            $mail = new Mail();
            return $mail->send($adminEmail, $subject, $message, true);
        } catch (Exception $e) {
            // Log error but don't fail the payment process
            error_log("Email notification failed: " . $e->getMessage());
            return false;
        }
    }
}
