<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
$doc_root = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
$is_ajax = isset($_GET['ajax']) && $_GET['ajax'] === 'get_invoices';

chdir($doc_root);
$config_path = $doc_root . '/config.php';
if (file_exists($config_path)) { require_once $config_path; } 
else { 
    if($is_ajax) { die(json_encode(['status' => 'error', 'message' => 'config.php not found!'])); }
    die("Error: config.php not found."); 
}

if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    if($is_ajax) { die(json_encode(['status' => 'error', 'message' => 'Unauthorized'])); }
    header("Location: /login/"); exit();
}

$user_id = $_SESSION['user_id'];

// AJAX API
if ($is_ajax) {
    error_reporting(E_ALL); ini_set('display_errors', 1); header('Content-Type: application/json');
    if (!isset($conn)) { echo json_encode(['status' => 'error', 'message' => 'DB connection missing.']); exit(); }

    // theme_color কলামটিও সিলেক্ট করা হয়েছে যাতে প্রিভিউতে ইনভয়েসের আসল কালার দেখানো যায়
    $stmt = $conn->prepare("SELECT id, invoice_number, to_text, invoice_date, currency_symbol, total_due, theme_color FROM user_invoices WHERE user_id = ? ORDER BY id DESC");
    if(!$stmt) { echo json_encode(['status' => 'error', 'message' => 'SQL Error: ' . $conn->error]); exit(); }

    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $invoices =[];
    while ($row = $result->fetch_assoc()) {
        $client_lines = explode("\n", trim($row['to_text'] ?? ''));
        $client_name = !empty(trim($client_lines[0])) ? trim($client_lines[0]) : 'Unknown Client';
        $inv_num = !empty(trim($row['invoice_number'])) ? $row['invoice_number'] : 'INV-' . $row['id'];
        
        $invoices[] =[
            'id' => $row['id'],
            'invoice_number' => $inv_num,
            'amount' => number_format((float)($row['total_due'] ?? 0), 2),
            'currency' => $row['currency_symbol'] ?? '$',
            'theme_color' => $row['theme_color'] ?? '#10b981',
            'client_name' => $client_name,
            'date' => date('M d, Y', strtotime($row['invoice_date'] ?? 'now')),
            'status' => 'Generated'
        ];
    }
    $stmt->close();
    usleep(200000); // হালকা লোডিং ডিলে
    echo json_encode(['status' => 'success', 'data' => $invoices]); exit();
}

// HTML 
$page_title = "Invoice Settings | Free Invoice Generator";
$header_path = $doc_root . '/header.php';
if (file_exists($header_path)) { require_once $header_path; } 
?>

<style>
    body { background-color: #f1f5f9; font-family: 'Inter', sans-serif; margin: 0; }
    /* চওড়া করার জন্য max-width বাড়ানো হয়েছে */
    .dashboard-wrapper { max-width: 1550px; margin: 40px auto; padding: 0 30px; min-height: 75vh; }
    
    .page-header-container { background: #ffffff; padding: 30px 40px; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.03); border: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 40px; position: relative; overflow: hidden;}
    .page-header-container::before { content: ''; position: absolute; left: 0; top: 0; height: 100%; width: 6px; background: linear-gradient(to bottom, #10b981, #059669); }
    .header-text h1 { font-size: 28px; font-weight: 800; color: #0f172a; margin: 0 0 8px 0; letter-spacing: -0.5px;}
    .header-text p { font-size: 15px; color: #64748b; margin: 0; font-weight: 500;}
    .btn-create { background: linear-gradient(135deg, #10b981, #059669); color: #fff; text-decoration: none; padding: 14px 28px; border-radius: 10px; font-weight: 700; font-size: 15px; display: flex; align-items: center; gap: 10px; transition: 0.3s; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.25);}
    .btn-create:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(16, 185, 129, 0.35); color: white;}

    /* গ্রিড কলাম চওড়া করা হয়েছে (minmax 320px) */
    .invoice-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 25px; }
    @media (max-width: 768px) { 
        .invoice-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px; } 
        .page-header-container { flex-direction: column; align-items: flex-start; gap: 20px; padding: 25px; }
        .btn-create { width: 100%; justify-content: center; box-sizing: border-box;}
    }

    /* কার্ডের উচ্চতা এবং ডিজাইন আপডেট */
    .inv-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 20px; display: flex; flex-direction: column; justify-content: space-between; transition: all 0.3s ease; box-shadow: 0 10px 25px rgba(0,0,0,0.02); min-height: 380px; position: relative; }
    .inv-card:hover { transform: translateY(-5px); box-shadow: 0 15px 35px rgba(0,0,0,0.08); border-color: #cbd5e1; }

    /* --- পিডিএফ প্রিভিউ এর সিএসএস --- */
    .mini-pdf-preview {
        background: #fff; border: 1px solid #e2e8f0; border-radius: 6px; height: 160px; margin-bottom: 20px; 
        padding: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); position: relative; overflow: hidden;
        display: flex; flex-direction: column; font-family: 'Courier New', Courier, monospace;
    }
    .mini-pdf-header { display: flex; justify-content: space-between; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #f1f5f9; }
    .mini-pdf-title { font-size: 10px; font-weight: bold; color: #334155; }
    .mini-pdf-lines { flex-grow: 1; }
    .line-box { height: 4px; background: #e2e8f0; border-radius: 2px; margin-bottom: 6px; }
    .mini-pdf-footer { text-align: right; font-size: 11px; font-weight: bold; color: #0f172a; border-top: 1px solid #f1f5f9; padding-top: 6px; }
    /* ফেড ইফেক্ট যাতে দেখতে অরিজিনাল লাগে */
    .pdf-fade { position: absolute; bottom: 0; left: 0; width: 100%; height: 60px; background: linear-gradient(to bottom, transparent, #ffffff); }

    .inv-info { margin-bottom: 15px; flex-grow: 1;}
    .inv-header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
    .inv-id { font-size: 13px; font-weight: 700; color: #475569;}
    .inv-amount { font-size: 26px; font-weight: 800; color: #0f172a; margin: 0 0 5px 0; }
    .inv-client { font-size: 14px; font-weight: 600; color: #64748b; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}

    .inv-actions { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; border-top: 1px dashed #e2e8f0; padding-top: 20px; }
    .action-btn { background: #f8fafc; color: #64748b; border: 1px solid #e2e8f0; border-radius: 8px; height: 40px; display: flex; justify-content: center; align-items: center; cursor: pointer; transition: 0.2s; text-decoration: none; font-size: 15px; }
    .action-btn:hover { background: #ffffff; }
    .btn-edit:hover { color: #3b82f6; border-color: #bfdbfe; background: #eff6ff;}
    .btn-share:hover { color: #8b5cf6; border-color: #ddd6fe; background: #f5f3ff;}
    .btn-email:hover { color: #10b981; border-color: #a7f3d0; background: #ecfdf5;}
    .btn-delete:hover { color: #ef4444; border-color: #fecaca; background: #fef2f2;}

    .skeleton { background: #e2e8f0; background-image: linear-gradient(90deg, #e2e8f0 0px, #f1f5f9 40px, #e2e8f0 80px); background-size: 200% 100%; animation: shimmer 1.5s infinite linear; border-radius: 6px; }
    @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
</style>

<div class="dashboard-wrapper">
    <div class="page-header-container">
        <div class="header-text">
            <h1>Invoice Settings</h1>
            <p>Manage, edit, and securely share your generated invoices.</p>
        </div>
        <a href="/dashboard/create/" class="btn-create"><i class="fas fa-magic"></i> Create New Invoice</a>
    </div>

    <div class="invoice-grid" id="invoiceGrid">
        <?php for($i=0; $i<6; $i++): ?>
        <div class="inv-card">
            <div class="skeleton" style="height: 160px; margin-bottom: 20px; border-radius: 6px;"></div>
            <div class="skeleton" style="height: 20px; width: 40%; margin-bottom: 10px;"></div>
            <div class="skeleton" style="height: 35px; width: 80%; margin-bottom: 10px;"></div>
            <div style="flex-grow:1;"></div>
            <div class="inv-actions">
                <div class="skeleton action-btn"></div><div class="skeleton action-btn"></div>
                <div class="skeleton action-btn"></div><div class="skeleton action-btn"></div>
            </div>
        </div>
        <?php endfor; ?>
    </div>
</div>

<div id="toast" style="visibility: hidden; min-width: 250px; background-color: #10b981; color: #fff; text-align: center; border-radius: 8px; padding: 16px; position: fixed; z-index: 1000; left: 50%; bottom: 30px; transform: translateX(-50%); font-size: 15px; font-weight: 600; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4); opacity: 0; transition: opacity 0.3s, bottom 0.3s;">
    <i class="fas fa-check-circle"></i> <span id="toast-msg">Action Successful!</span>
</div>

<script>
    document.addEventListener("DOMContentLoaded", fetchInvoices);

    function fetchInvoices() {
        fetch(window.location.pathname + '?ajax=get_invoices')
            .then(res => res.json())
            .then(data => {
                const grid = document.getElementById('invoiceGrid');
                if(data.status === 'error') { throw new Error(data.message); }
                grid.innerHTML = ''; 

                if(data.status === 'success' && data.data.length > 0) {
                    data.data.forEach(inv => {
                        let shareLink = window.location.origin + '/view.php?id=' + inv.id;
                        
                        let cardHTML = `
                            <div class="inv-card" style="border-top: 4px solid ${inv.theme_color};">
                                
                                <!-- PDF Style Miniature Preview -->
                                <div class="mini-pdf-preview">
                                    <div class="mini-pdf-header">
                                        <div class="mini-pdf-title" style="color: ${inv.theme_color};">INVOICE<br><span style="color:#64748b; font-weight:normal;">#${inv.invoice_number}</span></div>
                                        <div style="text-align:right; font-size:9px; color:#94a3b8;">${inv.date}</div>
                                    </div>
                                    <div class="mini-pdf-lines">
                                        <div style="font-size:9px; color:#64748b; margin-bottom:5px;">Bill To: <b style="color:#334155;">${inv.client_name}</b></div>
                                        <div class="line-box" style="width: 100%;"></div>
                                        <div class="line-box" style="width: 80%;"></div>
                                        <div class="line-box" style="width: 90%;"></div>
                                        <div class="line-box" style="width: 60%;"></div>
                                    </div>
                                    <div class="mini-pdf-footer">Total: ${inv.currency}${inv.amount}</div>
                                    <div class="pdf-fade"></div>
                                </div>

                                <div class="inv-info">
                                    <div class="inv-header-row">
                                        <span class="inv-id">#${inv.invoice_number}</span>
                                        <span style="font-size:11px; font-weight:700; color:#10b981;"><i class="fas fa-check-circle"></i> Generated</span>
                                    </div>
                                    <h3 class="inv-amount">${inv.currency}${inv.amount}</h3>
                                    <p class="inv-client" title="${inv.client_name}"><i class="far fa-user" style="color:#94a3b8;"></i> ${inv.client_name}</p>
                                </div>

                                <div class="inv-actions">
                                    <a href="/dashboard/edit-invoice.php?id=${inv.id}" class="action-btn btn-edit" title="Edit Invoice"><i class="fas fa-pen"></i></a>
                                    <button class="action-btn btn-share" title="Copy Secure Link" onclick="copyShareLink('${shareLink}')"><i class="fas fa-link"></i></button>
                                    <a href="/dashboard/send-email.php?id=${inv.id}" class="action-btn btn-email" title="Send via Email"><i class="fas fa-envelope"></i></a>
                                    <button class="action-btn btn-delete" title="Delete Invoice" onclick="deleteInvoice(${inv.id})"><i class="fas fa-trash-alt"></i></button>
                                </div>
                            </div>
                        `;
                        grid.insertAdjacentHTML('beforeend', cardHTML);
                    });
                } else {
                    grid.innerHTML = `<div style="grid-column: 1/-1; text-align:center; padding:50px; background:#fff; border-radius:12px;"><h3>No invoices found</h3></div>`;
                }
            })
            .catch(err => alert("Error: " + err.message));
    }

    function copyShareLink(link) {
        navigator.clipboard.writeText(link).then(() => showToast('Secure Link Copied!'));
    }

    // ডিলিট API কল করার ফাংশন
    function deleteInvoice(id) {
        if(confirm("Are you sure you want to delete this invoice permanently?")) {
            // API ফোল্ডার থেকে ফাইল কল করা হচ্ছে
            fetch('/api/delete_invoice.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + id
            })
            .then(res => res.json())
            .then(data => {
                if(data.status === 'success') {
                    showToast('Invoice deleted successfully!');
                    fetchInvoices(); // রিলোড ছাড়াই কার্ড মুছে যাবে
                } else {
                    alert("Failed to delete: " + data.message);
                }
            }).catch(err => alert('Network error. Could not delete.'));
        }
    }

    function showToast(msg) {
        let toast = document.getElementById("toast");
        document.getElementById("toast-msg").innerText = msg;
        toast.style.visibility = "visible"; toast.style.opacity = "1"; toast.style.bottom = "50px";
        setTimeout(() => { 
            toast.style.opacity = "0"; toast.style.bottom = "30px";
            setTimeout(() => { toast.style.visibility = "hidden"; }, 300);
        }, 3000);
    }
</script>

<?php 
$footer_path = $doc_root . '/footer.php';
if (file_exists($footer_path)) { require_once $footer_path; } 
?>