<?php
session_start();

// --- CONFIGURATION ---
$valid_password = "627707"; 

// --- LOGOUT LOGIC ---
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// --- LOGIN LOGIC ---
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pass = $_POST['password'] ?? '';
    if ($pass === $valid_password) {
        $_SESSION['spartanz_logged_in'] = true;
        header("Location: index.php");
        exit;
    } else {
        $error = "Incorrect PIN";
    }
}

// --- SECURITY CHECK ---
if (!isset($_SESSION['spartanz_logged_in']) || $_SESSION['spartanz_logged_in'] !== true):
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spartanz Secured Login</title>
    <style>
        body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background: #333; height: 100vh; display: flex; align-items: center; justify-content: center; margin: 0; }
        .login-box { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 10px 25px rgba(0,0,0,0.5); text-align: center; width: 300px; }
        h2 { margin-top: 0; color: #333; margin-bottom: 20px; }
        input { width: 100%; padding: 12px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 5px; font-size: 18px; box-sizing: border-box; text-align: center; letter-spacing: 3px; }
        button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 5px; font-size: 16px; font-weight: bold; cursor: pointer; transition: background 0.2s; }
        button:hover { background: #0056b3; }
        .error { color: red; margin-top: 15px; font-size: 14px; background: #ffe6e6; padding: 10px; border-radius: 4px; }
    </style>
</head>
<body>
    <div class="login-box">
        <h2>Spartanz System</h2>
        <form method="POST">
            <input type="password" name="password" placeholder="ENTER PIN" autofocus required>
            <button type="submit">SECURE LOGIN</button>
        </form>
        <?php if($error): ?><div class="error"><?php echo $error; ?></div><?php endif; ?>
    </div>
</body>
</html>
<?php
exit;
endif;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spartanz Cloud System</title>
    <style>
        /* --- GLOBAL STYLES --- */
        body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: #555; margin: 0; padding: 0; display: flex; justify-content: center; min-height: 100vh; }
        
        /* --- MAIN APP --- */
        #appContainer { display: flex; width: 100%; justify-content: center; padding: 20px; box-sizing: border-box; }

        /* --- CONTROLS BOX --- */
        .controls { position: fixed; top: 20px; left: 20px; width: 340px; background: white; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); z-index: 1000; display: flex; flex-direction: column; max-height: 90vh; }
        .drag-header { background-color: #333; color: white; padding: 10px 15px; cursor: grab; font-size: 14px; font-weight: bold; display: flex; justify-content: space-between; align-items: center; }
        .drag-header:active { cursor: grabbing; }
        .tab-header { display: flex; background-color: #eee; border-bottom: 1px solid #ccc; }
        .tab-btn { flex: 1; padding: 10px; border: none; background: none; cursor: pointer; font-weight: bold; color: #666; border-bottom: 3px solid transparent; }
        .tab-btn.active { color: #333; border-bottom: 3px solid #007bff; background-color: white; }
        .tab-content { padding: 15px; overflow-y: auto; display: none; flex-grow: 1; }
        .tab-content.active { display: block; }
        .controls textarea { width: 100%; height: 150px; border: 1px solid #ccc; padding: 10px; font-size: 11px; box-sizing: border-box; resize: vertical; font-family: monospace; background-color: #f9f9f9; margin-bottom: 10px; }
        .btn-group { display: flex; gap: 5px; margin-top: 5px; }
        .btn { flex: 1; padding: 10px; border: none; border-radius: 4px; cursor: pointer; font-weight: bold; font-size: 12px; color: white; }
        .btn-green { background-color: #28a745; } .btn-blue { background-color: #007bff; } .btn-orange { background-color: #fd7e14; } .btn-red { background-color: #dc3545; } .btn-dark { background-color: #343a40; }
        .note { font-size: 11px; color: #666; margin-bottom: 8px; line-height: 1.4; }
        
        /* --- HISTORY LIST --- */
        .history-list { list-style: none; padding: 0; margin: 0; }
        .history-item { border-bottom: 1px solid #eee; padding: 10px 0; display: flex; justify-content: space-between; align-items: center; }
        .history-info { font-size: 11px; line-height: 1.4; color: #333; }
        .history-info strong { color: #000; font-size: 12px; }
        .history-actions { display: flex; gap: 5px; }
        .btn-xs { padding: 4px 8px; font-size: 10px; border-radius: 3px; cursor: pointer; color: white; border: none; }

        /* --- INVOICE PAGE --- */
        .page { 
            width: 210mm; 
            min-height: 297mm; 
            background: white; 
            box-shadow: 0 0 20px rgba(0,0,0,0.5); 
            position: relative; 
            display: flex; 
            flex-direction: column; 
            box-sizing: border-box; 
            flex-shrink: 0; 
        }
        
        /* ADJUSTED PADDING FOR BETTER FIT */
        .invoice-header { background-color: #FFF8DC; padding: 15px 35px 10px 35px; border-bottom: 1px solid #ddd; }
        
        .top-title { font-size: 26px; font-weight: bold; text-transform: uppercase; margin-bottom: 8px; letter-spacing: 1px; }
        .header-columns { display: flex; justify-content: space-between; font-size: 9px; line-height: 1.3; color: #333; }
        .col-left, .col-mid { width: 35%; } .col-right { width: 25%; text-align: right; }
        .company-name { font-weight: bold; font-size: 10px; margin-bottom: 2px; }
        .label { font-weight: bold; color: #000; }
        
        /* TIGHTER BODY PADDING */
        .invoice-body { padding: 5px 35px; flex-grow: 1; }
        
        table { width: 100%; border-collapse: collapse; font-size: 9px; table-layout: fixed; }
        
        thead { display: table-header-group; } 
        tr { page-break-inside: avoid; }
        
        thead th { text-align: left; border-bottom: 2px solid #ccc; padding: 4px 2px; text-transform: uppercase; font-weight: bold; color: #444; font-size: 8px; }
        th:nth-child(1) { width: 18%; } th:nth-child(2) { width: 35%; } th:nth-child(3) { width: 12%; }
        th:nth-child(4) { width: 5%; text-align: center; } th:nth-child(5) { width: 15%; text-align: right; } th:nth-child(6) { width: 15%; text-align: right; }
        
        /* SLIGHTLY TIGHTER ROW PADDING (2px instead of 3px) */
        tbody td { padding: 2px 2px; border-bottom: 1px solid #f0f0f0; vertical-align: top; color: #333; }
        td:nth-child(4) { text-align: center; } td:nth-child(5), td:nth-child(6) { text-align: right; }

        .total-section { padding: 5px 35px; text-align: right; font-size: 11px; font-weight: bold; margin-bottom: 5px; page-break-inside: avoid; }
        .total-line { border-top: 2px solid #eee; padding-top: 5px; display: flex; justify-content: space-between; margin-left: auto; width: 30%; }
        
        .invoice-footer { background-color: #FFF8DC; padding: 10px 35px; font-size: 9px; color: #333; border-top: 1px solid #ddd; page-break-inside: avoid; }
        .footer-title { font-weight: bold; margin-bottom: 3px; font-size: 10px; }

        [contenteditable="true"]:hover { background-color: rgba(255, 255, 0, 0.1); outline: 1px dashed #ccc; cursor: text; }

        /* --- MOBILE --- */
        @media screen and (max-width: 900px) {
            body { flex-direction: column; align-items: center; }
            #appContainer { padding-top: 380px; }
            .controls { width: 90%; left: 5%; top: 10px; height: 350px; }
            .page { transform: scale(0.6); transform-origin: top center; margin-bottom: -100mm; }
        }

        /* --- PRINT (OPTIMIZED TO FIT) --- */
        @media print {
            @page { 
                size: A4 portrait; 
                margin: 4mm; /* KEY FIX: Reduced print margins to 4mm to fit footer */
            }
            
            body { background: white; display: block; }
            .controls { display: none !important; }
            #appContainer { display: block; padding: 0; }
            
            .page { 
                width: 100%; 
                height: 100%; /* Force height utilization */
                box-shadow: none; 
                margin: 0; 
                display: block;
            }
            
            .invoice-body { padding: 0; }
            /* Reduce padding further on print to ensure fit */
            .invoice-header { padding: 10px 0 5px 0; }
            .invoice-footer { padding: 5px 0; }
            
            [contenteditable="true"]:hover { background: none; outline: none; }
            .invoice-header, .invoice-footer { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }
    </style>
</head>
<body>

<div id="appContainer">
    <div class="controls" id="draggableBox">
        <div class="drag-header" id="dragHandle">
            <span>Spartanz System v15 (Perfect Fit)</span>
            <div style="display:flex; gap:10px; align-items:center;">
                <span style="font-size:10px; opacity:0.7;">(Drag)</span>
                <a href="?logout=true" style="color:white; font-size:10px; text-decoration:none; border:1px solid rgba(255,255,255,0.3); padding:2px 6px; border-radius:3px;">LOGOUT</a>
            </div>
        </div>
        <div class="tab-header">
            <button class="tab-btn active" onclick="switchTab('create')">Create</button>
            <button class="tab-btn" onclick="switchTab('history')">Database</button>
        </div>

        <div id="tab-create" class="tab-content active">
            <textarea id="inputData" placeholder="Item / description..."></textarea>
            <div class="btn-group">
                <button class="btn btn-red" onclick="clearData()">Clear</button>
                <button class="btn btn-green" onclick="generateInvoice()">Generate</button>
            </div>
            <div class="btn-group">
                <button class="btn btn-orange" onclick="saveToDatabase()">Save to Cloud</button>
                <button class="btn btn-blue" onclick="window.print()">Save PDF</button>
            </div>
        </div>

        <div id="tab-history" class="tab-content">
            <div style="text-align:center; padding-bottom:10px;">
                <button class="btn btn-blue" style="width:100%; font-size:10px;" onclick="loadFromDatabase()">Refresh List</button>
            </div>
            <div id="historyContainer">
                <p style="text-align:center; padding:20px; font-size:11px; color:#666;">Loading...</p>
            </div>
        </div>
    </div>

    <div class="page" id="invoicePage">
        <div class="invoice-header">
            <div class="top-title">INVOICE</div>
            <div class="header-columns">
                <div class="col-left" contenteditable="true" id="edit-from">
                    <div class="company-name">Spartanz Management</div>
                    <div>Jalan Taman Ibu Kota</div>
                    <div>Taman Setapak Indah</div>
                    <div>53300 Kuala Lumpur</div>
                    <div>Email: ahkuan241136@gmail.com</div>
                    <div>Phone: 017-8724946</div>
                </div>
                <div class="col-mid" contenteditable="true" id="edit-to">
                    <div class="label">Billed To</div>
                    <div>Chuan Sin Sdn. Bhd.</div>
                    <div>NO 1, Jalan Sitar 33/6</div>
                    <div>Seksyen 33, 40400 Shah Alam</div>
                </div>
                <div class="col-right">
                    <div style="margin-bottom: 5px;">
                        <span class="label">INVOICE #</span> &nbsp;&nbsp; 
                        <span contenteditable="true" id="edit-inv-num">31122025</span>
                    </div>
                    <div>
                        <span class="label">INVOICE DATE</span> &nbsp;&nbsp; 
                        <span contenteditable="true" id="edit-date">31/12/2025</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="invoice-body">
            <table id="invoiceTable">
                <thead><tr><th>ITEM</th><th>DESCRIPTION</th><th>DATE</th><th>DAYS</th><th>RATE</th><th>AMOUNT</th></tr></thead>
                <tbody id="tableBody"><tr><td colspan="6" style="text-align:center; padding:20px; color:#999;">Waiting...</td></tr></tbody>
            </table>
        </div>
        <div class="total-section">
            <div class="total-line"><span>TOTAL</span><span id="grandTotal">MYR 0.00</span></div>
        </div>
        <div class="invoice-footer">
            <div class="footer-title">Payment Method :</div>
            <div style="font-weight:bold;">SPARTANZ MANAGEMENT & CONSULTATION</div>
            <div>AMBANK</div>
            <div>8881058812552</div>
        </div>
    </div>
</div>

<script>
    const API_URL = "api.php"; 
    window.onload = function() { loadFromDatabase(); };

    async function saveToDatabase() {
        const input = document.getElementById('inputData').value;
        if(!input) { alert("Nothing to save!"); return; }
        
        const payload = {
            inputData: input,
            invNum: document.getElementById('edit-inv-num').innerText,
            date: document.getElementById('edit-date').innerText,
            billTo: document.getElementById('edit-to').innerHTML,
            from: document.getElementById('edit-from').innerHTML,
            total: document.getElementById('grandTotal').innerText
        };

        try {
            const res = await fetch(API_URL, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(payload)
            });
            const result = await res.json();
            if(result.status === 'success') {
                alert("Saved to Database Successfully!");
                loadFromDatabase(); 
            } else {
                alert("Error saving: " + (result.message || "Unknown error"));
            }
        } catch(e) { console.error(e); alert("Connection Error."); }
    }

    async function loadFromDatabase() {
        try {
            const res = await fetch(API_URL);
            const invoices = await res.json();
            const container = document.getElementById('historyContainer');
            if(invoices.length === 0) {
                container.innerHTML = '<p class="note" style="text-align:center; padding:20px;">No records found.</p>';
                return;
            }
            let html = '<ul class="history-list">';
            invoices.forEach(inv => {
                const safeData = encodeURIComponent(JSON.stringify(inv.full_data)); 
                html += `
                    <li class="history-item">
                        <div class="history-info">
                            <strong>#${inv.invoice_number}</strong> - ${inv.invoice_date}<br>
                            ${inv.client_name} (${inv.total_amount})
                        </div>
                        <div class="history-actions">
                            <button class="btn-xs btn-blue" onclick="loadRecord('${safeData}')">Load</button>
                            <button class="btn-xs btn-red" onclick="deleteRecord(${inv.id})">X</button>
                        </div>
                    </li>`;
            });
            html += '</ul>';
            container.innerHTML = html;
        } catch(e) { console.error(e); }
    }

    async function deleteRecord(id) {
        if(!confirm("Permanently delete this invoice?")) return;
        try {
            const res = await fetch(`${API_URL}?action=delete&id=${id}`);
            const result = await res.json();
            if(result.status === 'success') loadFromDatabase();
            else alert("Failed to delete.");
        } catch(e) { alert("Connection Error"); }
    }

    function loadRecord(encodedData) {
        const data = JSON.parse(decodeURIComponent(encodedData));
        document.getElementById('inputData').value = data.inputData;
        document.getElementById('edit-inv-num').innerText = data.invNum;
        document.getElementById('edit-date').innerText = data.date;
        document.getElementById('edit-to').innerHTML = data.billTo;
        document.getElementById('edit-from').innerHTML = data.from;
        generateInvoice();
        switchTab('create');
    }

    function switchTab(t) {
        document.querySelectorAll('.tab-content').forEach(e => e.classList.remove('active'));
        document.querySelectorAll('.tab-btn').forEach(e => e.classList.remove('active'));
        document.getElementById(`tab-${t}`).classList.add('active');
        const btns = document.querySelectorAll('.tab-btn');
        if(t==='create') btns[0].classList.add('active'); else btns[1].classList.add('active');
    }
    function clearData() { document.getElementById('inputData').value = ""; }
    function cleanCurrency(s) { if(!s)return 0; return parseFloat(s.replace(/RM|MYR|\s|,/gi, "").replace(/\u00A0/g, "")) || 0; }

    function generateInvoice() {
        const raw = document.getElementById('inputData').value;
        const blocks = raw.split(/Item\s*\/\s*description/i);
        const tbody = document.getElementById('tableBody');
        tbody.innerHTML = "";
        let grandTotal = 0; let hasData = false;

        for (let i=1; i<blocks.length; i++) {
            let block = blocks[i].trim();
            if(!block) continue;
            
            // --- EMOJI REMOVER ---
            block = block.replace(/[\u{1F600}-\u{1F64F}]/gu, "") 
                         .replace(/[\u{1F300}-\u{1F5FF}]/gu, "") 
                         .replace(/[\u{1F680}-\u{1F6FF}]/gu, "") 
                         .replace(/[\u{1F1E0}-\u{1F1FF}]/gu, "");

            hasData = true;
            let lines = block.split('\n');
            let itemLine = lines[0].trim().replace(/^\d+\)\s*/, ""); 
            let itemCat="", itemDesc="";
            if(itemLine.includes(" - ")) {
                let parts = itemLine.split(" - ");
                itemCat = parts[0].toUpperCase(); itemDesc = parts.slice(1).join(" - ").toUpperCase();
            } else {
                itemCat = "GENERAL"; itemDesc = itemLine.toUpperCase();
                if(itemDesc.includes("LOGISTIC")) itemCat="LOGISTIC";
                if(itemDesc.includes("STAFF")) itemCat="STAFF SAMPLING";
            }

            let dateVal="", daysVal="", rateVal="", amountVal="";
            let amountNum=0;

            const dateMatch = block.match(/Date\s*-\s*(.*)/i);
            const daysMatch = block.match(/Days\s*-\s*(.*)/i);
            const rateMatch = block.match(/Item rate\s*-\s*(.*)/i);
            const amountMatch = block.match(/Amount\s*-\s*(.*)/i);

            if (dateMatch) dateVal = dateMatch[1].trim(); 
            if (daysMatch) daysVal = daysMatch[1].trim();
            if (rateMatch) rateVal = rateMatch[1].trim().toUpperCase();

            if (rateVal && !rateVal.startsWith("RM") && !rateVal.startsWith("MYR")) rateVal = "RM " + rateVal;
            rateVal = rateVal.replace("MYR", "MYR ");

            if (amountMatch) {
                let rawAmt = amountMatch[1].trim();
                if (rawAmt.includes(',')) {
                    rawAmt.split(',').forEach(p => amountNum += cleanCurrency(p));
                } else {
                    amountNum = cleanCurrency(rawAmt);
                }
                amountVal = "MYR " + amountNum.toFixed(2);
            }
            grandTotal += amountNum;
            tbody.innerHTML += `<tr><td>${itemCat}</td><td>${itemDesc}</td><td>${dateVal}</td><td>${daysVal}</td><td>${rateVal.replace('RM','MYR')}</td><td>${amountVal}</td></tr>`;
        }
        if(hasData) document.getElementById('grandTotal').innerText = "MYR " + grandTotal.toLocaleString('en-US', {minimumFractionDigits: 2});
    }

    const dragBox = document.getElementById("draggableBox");
    const dragHandle = document.getElementById("dragHandle");
    let isDragging = false; let startX, startY, initialLeft, initialTop;
    dragHandle.addEventListener("mousedown", (e) => { isDragging=true; startX=e.clientX; startY=e.clientY; initialLeft=dragBox.offsetLeft; initialTop=dragBox.offsetTop; document.addEventListener("mousemove", onMouseMove); document.addEventListener("mouseup", onMouseUp); });
    function onMouseMove(e) { if(!isDragging)return; dragBox.style.left = `${initialLeft + e.clientX - startX}px`; dragBox.style.top = `${initialTop + e.clientY - startY}px`; }
    function onMouseUp() { isDragging=false; document.removeEventListener("mousemove", onMouseMove); document.removeEventListener("mouseup", onMouseUp); }
</script>

</body>
</html>