<?php
session_start();

// ১. ডাটাবেস কানেকশন
$servername = "localhost";
$username = "mobileh1_teams";
$password = 'de*tMX~5[.Ffwb7v'; 
$dbname = "mobileh1_teams";

$conn = new mysqli($servername, $username, $password, $dbname);

// বাংলা লেখা (Unicode) ঠিক করার জন্য
$conn->set_charset("utf8mb4");

if ($conn->connect_error) { die("Database Connection failed"); }

// ২. লগইন চেক
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("location: login.php");
    exit;
}

$id = isset($_GET['id']) ? $_GET['id'] : die("ID missing");

// ৩. স্ট্যাটাস আপডেট লজিক
if (isset($_POST['update_status'])) {
    $new_status = $_POST['order_status'];
    $update_stmt = $conn->prepare("UPDATE orders SET status = ? WHERE id = ?");
    $update_stmt->bind_param("si", $new_status, $id);
    $update_stmt->execute();
    echo "<script>window.location='order_view.php?id=$id';</script>";
}

// ৪. ডাটাবেস থেকে ডাটা আনা
$stmt = $conn->prepare("SELECT * FROM orders WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$order = $result->fetch_assoc();
if (!$order) { die("Order not found"); }
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice_#<?php echo $order['id']; ?></title>
    
    <!-- CSS & Fonts -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
    
    <!-- PDF Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    
    <style>
        :root { --primary: #ff4d6d; --bg: #f4f6f9; --text: #334155; }
        body { background: var(--bg); font-family: 'Hind Siliguri', sans-serif; color: var(--text); margin: 0; }
        
        .main-content { margin-left: 250px; width: calc(100% - 250px); min-height: 100vh; transition: 0.3s; }
        .content-body { padding: 30px; }

        /* ইনভয়েস কন্টেইনার - Responsive & PDF Friendly */
        #invoice-wrapper {
            max-width: 850px; /* Standard width for PDF */
            width: 100%;
            background: #fff;
            margin: 0 auto;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            overflow: hidden; /* Prevent cutting */
        }
        
        .inv-header { display: flex; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 20px; margin-bottom: 30px; }
        .logo-box { font-size: 26px; font-weight: 800; color: #1e293b; }
        .logo-box span { color: var(--primary); }

        .title-red { color: var(--primary); font-weight: 700; border-bottom: 1.5px solid #eee; padding-bottom: 6px; margin-bottom: 15px; font-size: 17px; }

        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 30px; }
        .info-box p { line-height: 1.6; font-size: 14px; margin-bottom: 0; color: #444; }

        .table-responsive-fix { width: 100%; overflow-x: auto; }
        .invoice-table { width: 100%; margin-bottom: 25px; border-collapse: collapse; min-width: 600px; }
        .invoice-table th { background: #f8fafc; color: #64748b; padding: 12px; font-size: 13px; border-bottom: 2px solid #edf2f7; text-align: left; }
        .invoice-table td { padding: 15px 12px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }

        .summary-flex { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 20px; margin-top: 15px; }
        .payment-meta-box { background: #fcfdfe; border: 1px solid #edf2f7; padding: 20px; border-radius: 12px; flex: 1; min-width: 300px; }
        .calc-box { flex: 1; min-width: 250px; }
        .calc-row { display: flex; justify-content: space-between; padding: 8px 0; font-size: 15px; }
        .due-row { border-top: 2px solid var(--primary); margin-top: 10px; padding-top: 10px; font-weight: 800; color: var(--primary); font-size: 19px; }

        .st-badge { padding: 4px 12px; border-radius: 50px; font-size: 10px; font-weight: 700; text-transform: uppercase; display: inline-block; }
        .st-approved { background: #ecfdf5; color: #065f46; }
        .st-pending { background: #fff8e1; color: #b45309; }
        .st-rejected { background: #fef2f2; color: #991b1b; }

        .status-update-box { background: #fff; padding: 20px; border-radius: 10px; margin: 0 auto 20px auto; max-width: 850px; border: 1px solid #eee; }
        .footer-actions { text-align: center; margin-top: 30px; padding-bottom: 50px; }
        .btn-download { background: #10b981; color: white; border: none; padding: 15px 45px; border-radius: 50px; font-weight: 700; cursor: pointer; transition: 0.3s; }
        .btn-download:hover { background: #0d9668; transform: translateY(-2px); }

        /* মোবাইল রেসপনসিভ এডজাস্টমেন্ট */
        @media (max-width: 991px) {
            .main-content { margin-left: 0; width: 100%; }
            .info-grid { grid-template-columns: 1fr; gap: 15px; }
            #invoice-wrapper { padding: 20px; }
            .inv-header { flex-direction: column; text-align: left !important; }
            .inv-header .text-end { text-align: left !important; margin-top: 10px; }
        }
    </style>
</head>
<body>

    <?php include 'sidebar.php'; ?>

    <main class="main-content">
        <?php include 'top_header.php'; ?>

        <div class="content-body">
            
            <div class="mb-3">
                <a href="orders_manage.php" class="btn btn-sm btn-outline-secondary rounded-pill px-3">
                    <i class="fas fa-arrow-left me-1"></i> পিছনে ফিরুন
                </a>
            </div>

            <!-- স্ট্যাটাস আপডেট -->
            <div class="status-update-box">
                <form action="" method="POST" class="row g-3 align-items-center">
                    <div class="col-auto">
                        <span class="small fw-bold">স্ট্যাটাস আপডেট করুন:</span>
                    </div>
                    <div class="col-auto">
                        <select name="order_status" class="form-select form-select-sm rounded-pill shadow-none">
                            <option value="Pending" <?php if($order['status'] == 'Pending') echo 'selected'; ?>>Pending</option>
                            <option value="Approved" <?php if($order['status'] == 'Approved') echo 'selected'; ?>>Approved</option>
                            <option value="Rejected" <?php if($order['status'] == 'Rejected') echo 'selected'; ?>>Rejected</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <button type="submit" name="update_status" class="btn btn-sm btn-dark rounded-pill px-3">আপডেট</button>
                    </div>
                </form>
            </div>

            <!-- ইনভয়েস এরিয়া -->
            <div id="invoice-render-area">
                <div id="invoice-wrapper">
                    <div class="inv-header">
                        <div class="logo-box">CODEXIO<span>BD</span></div>
                        <div class="text-end">
                            <h4 class="fw-bold mb-1" style="color:var(--primary)">অর্ডার ইনভয়েস</h4>
                            <p class="mb-0 text-muted small">আইডি: #<?php echo $order['id']; ?></p>
                            <p class="mb-0 text-muted small">তারিখ: <?php echo date('d M, Y', strtotime($order['created_at'])); ?></p>
                        </div>
                    </div>

                    <div class="info-grid">
                        <div class="info-box">
                            <div class="title-red">বিল প্রেরক:</div>
                            <p><strong>CodexioBD Digital Agency</strong><br>
                            গাজীপুর সদর, গাজীপুর<br>
                            ফোন: +৮৮০ ১৯১২ ৮৫৫৯৮৯</p>
                        </div>
                        <div class="info-box">
                            <div class="title-red">বিল প্রাপক:</div>
                            <p><strong><?php echo htmlspecialchars($order['client_name']); ?></strong><br>
                            ঠিকানা: <?php echo htmlspecialchars($order['address']); ?><br>
                            ফোন: <?php echo htmlspecialchars($order['mobile_number']); ?><br>
                            ইমেইল: <?php echo htmlspecialchars($order['email']); ?></p>
                        </div>
                    </div>

                    <div class="title-red">প্রজেক্টের বিস্তারিত তথ্য:</div>
                    <div class="table-responsive-fix">
                        <table class="invoice-table">
                            <thead>
                                <tr>
                                    <th width="60%">সার্ভিসের বিবরণ</th>
                                    <th width="20%">সময়সীমা</th>
                                    <th class="text-end">মূল্য (৳)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                        <h6 class="fw-bold mb-1"><?php echo htmlspecialchars($order['website_name']); ?></h6>
                                        <p class="text-muted small mb-1"><?php echo nl2br(htmlspecialchars($order['description'])); ?></p>
                                        <?php if($order['requirement_demo']): ?>
                                            <small class="text-primary"><i class="fas fa-link me-1"></i> ডেমো লিঙ্ক: <?php echo $order['requirement_demo']; ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <small>শুরু: <?php echo date('d M, Y', strtotime($order['project_start_date'])); ?></small><br>
                                        <small>সম্পন্ন: <?php echo ($order['project_end_date'] != '0000-00-00' && $order['project_end_date'] != '1970-01-01') ? date('d M, Y', strtotime($order['project_end_date'])) : 'চলমান'; ?></small>
                                    </td>
                                    <td class="text-end fw-bold"><?php echo number_format($order['total_price'], 2); ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="summary-flex">
                        <div class="payment-meta-box">
                            <div class="title-red" style="border:none; font-size: 14px; margin-bottom: 5px;">পেমেন্ট মেটা তথ্য:</div>
                            <table class="w-100 small">
                                <tr><td class="text-muted py-1">পেমেন্ট মেথড:</td><td class="fw-bold"><?php echo htmlspecialchars($order['payment_method']); ?></td></tr>
                                <tr><td class="text-muted py-1">প্রেরক নম্বর:</td><td class="fw-bold"><?php echo $order['sender_number'] ?: 'N/A'; ?></td></tr>
                                <tr><td class="text-muted py-1">ট্রানজেকশন আইডি:</td><td class="fw-bold text-uppercase"><?php echo $order['transaction_id'] ?: 'N/A'; ?></td></tr>
                                <tr><td class="text-muted py-1">অর্ডার স্ট্যাটাস:</td><td><span class="st-badge st-<?php echo strtolower($order['status']); ?>"><?php echo $order['status']; ?></span></td></tr>
                            </table>
                        </div>

                        <div class="calc-box">
                            <div class="calc-row"><span>সাব-টোটাল মূল্য:</span><span><?php echo number_format($order['total_price'], 2); ?> ৳</span></div>
                            <div class="calc-row"><span>অগ্রিম পরিশোধিত:</span><span class="text-success">- <?php echo number_format($order['advance_payment'], 2); ?> ৳</span></div>
                            <div class="calc-row due-row"><span>মোট বকেয়া (Due):</span><span><?php echo number_format($order['due_amount'], 2); ?> ৳</span></div>
                        </div>
                    </div>

                    <div style="margin-top: 50px; border-top: 1px solid #f1f5f9; padding-top: 15px; font-size: 11px; color: #94a3b8; text-align: center;">
                        <p>আমাদের ওপর আস্থা রাখার জন্য ধন্যবাদ। কোনো জিজ্ঞাসা থাকলে আমাদের ফোন করুন।</p>
                    </div>
                </div>
            </div>

            <div class="footer-actions">
                <button onclick="downloadPDF()" id="downloadBtn" class="btn btn-download shadow-lg">
                    <i class="fas fa-file-pdf me-2"></i> সরাসরি PDF ডাউনলোড করুন
                </button>
            </div>

        </div>
    </main>

    <script>
        function downloadPDF() {
            const element = document.getElementById('invoice-wrapper');
            const btn = document.getElementById('downloadBtn');
            
            // বাটন ডিজেবল করা
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> পিডিএফ তৈরি হচ্ছে...';
            btn.style.pointerEvents = 'none';

            const opt = {
                margin:       [10, 5, 10, 5], // [top, left, bottom, right]
                filename:     'Invoice_#<?php echo $order['id']; ?>.pdf',
                image:        { type: 'jpeg', quality: 0.98 },
                html2canvas:  { 
                    scale: 2, 
                    useCORS: true, 
                    letterRendering: true,
                    scrollY: 0
                },
                jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
            };

            // PDF জেনারেট করা
            html2pdf().set(opt).from(element).save().then(() => {
                btn.innerHTML = '<i class="fas fa-file-pdf me-2"></i> সরাসরি PDF ডাউনলোড করুন';
                btn.style.pointerEvents = 'auto';
            }).catch(err => {
                console.error(err);
                btn.innerHTML = 'ত্রুটি হয়েছে, পুনরায় চেষ্টা করুন';
                btn.style.pointerEvents = 'auto';
            });
        }
    </script>
</body>
</html>