<!DOCTYPE html>
<html lang="hi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AizaTech - Service Manager</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:system-ui,sans-serif;background:linear-gradient(135deg,#667eea,#764ba2);min-height:100vh;}
.auth-container{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px;}
.auth-card{max-width:400px;width:100%;background:white;border-radius:48px;padding:40px 28px;text-align:center;}
.logo-icon{width:70px;height:70px;background:linear-gradient(135deg,#667eea,#764ba2);border-radius:20px;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;}
.logo-icon svg{width:36px;height:36px;stroke:white;}
h1{font-size:26px;color:#1a1a2e;}
.subhead{font-size:12px;color:#888;margin-bottom:32px;}
.input-field{width:100%;padding:14px 20px;border:1px solid #e2e8f0;border-radius:60px;margin-bottom:12px;background:#f8fafc;font-size:14px;}
.btn-primary{width:100%;background:linear-gradient(135deg,#667eea,#764ba2);border:none;border-radius:60px;padding:14px;color:white;font-weight:bold;margin:16px 0;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:10px;}
.btn-outline{width:100%;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:60px;padding:12px;cursor:pointer;font-weight:500;}
.divider{color:#aaa;margin:16px 0;font-size:12px;}
.status{padding:10px;border-radius:12px;margin-top:12px;font-size:13px;}
.dashboard{display:none;background:#f1f5f9;min-height:100vh;padding:20px;}
.dashboard.active{display:block;}
.dash-header{background:white;border-radius:28px;padding:16px 20px;display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;}
.welcome h3{font-size:12px;color:#888;}
.welcome h2{font-size:22px;color:#1a1a2e;}
.logout-btn{background:#fee2e2;border:none;padding:8px 20px;border-radius:40px;color:#dc2626;cursor:pointer;}
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:20px;}
.stat-card{background:white;border-radius:20px;padding:14px 6px;text-align:center;}
.stat-number{font-size:22px;font-weight:800;color:#667eea;}
.stat-label{font-size:10px;color:#888;margin-top:5px;}
.tabs{display:flex;gap:8px;background:white;padding:6px;border-radius:60px;margin-bottom:20px;}
.tab{flex:1;padding:10px;border:none;background:transparent;border-radius:50px;font-weight:600;cursor:pointer;}
.tab.active{background:#667eea;color:white;}
.panel{display:none;}
.panel.active{display:block;}
.client-card{background:white;border-radius:24px;padding:16px;margin-bottom:12px;}
.client-name{font-size:17px;font-weight:700;color:#1a1a2e;}
.client-detail{font-size:12px;color:#888;margin:6px 0;}
.client-stats{display:flex;justify-content:space-between;margin:12px 0;padding:8px 0;border-top:1px solid #eee;border-bottom:1px solid #eee;}
.paid{color:#10b981;font-weight:600;}
.due{color:#f59e0b;font-weight:600;}
.btn-sm{padding:8px 16px;border-radius:30px;border:none;background:#667eea;color:white;cursor:pointer;}
.form-card{background:white;border-radius:24px;padding:20px;}
.form-group{margin-bottom:14px;}
.form-group label{display:block;color:#666;font-size:12px;margin-bottom:5px;}
.form-group input,.form-group select{width:100%;padding:12px;border:1px solid #e2e8f0;border-radius:16px;background:#f8fafc;font-size:14px;}
.add-btn{width:100%;background:#10b981;border:none;border-radius:60px;padding:12px;color:white;font-weight:bold;margin-top:8px;cursor:pointer;}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);align-items:center;justify-content:center;z-index:1000;padding:20px;}
.modal.show{display:flex;}
.modal-content{background:white;border-radius:28px;padding:24px;max-width:380px;width:100%;max-height:80vh;overflow-y:auto;}
.payment-item{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #eee;}
.empty-state{text-align:center;color:#aaa;padding:30px;}
.hidden{display:none;}
</style>
</head>
<body>

<!-- LOGIN PAGE -->
<div id="authPage" class="auth-container ">
  <div class="auth-card">
    <div class="logo-icon"><svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="1.8"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg></div>
    <h1>AizaTech</h1>
    <div class="subhead">IT Service Management</div>
    <input type="text" id="loginUser" class="input-field" placeholder="Username" value="admin">
    <button id="fpLoginBtn" class="btn-primary">🔐 Fingerprint Login</button>
    <div class="divider">──── OR ────</div>
    <input type="password" id="loginPass" class="input-field" placeholder="Password">
    <button id="pwLoginBtn" class="btn-outline">Password Login</button>
    <div id="statusMsg" class="status"></div>
  </div>
</div>

<!-- DASHBOARD -->
<div id="dashboardPage" class="dashboard ">
  <div class="dash-header">
    <div><h3>Welcome,</h3><h2 id="userName">Admin</h2></div>
    <button id="logoutBtn" class="logout-btn">Logout</button>
  </div>
  <div class="stats-row">
    <div class="stat-card"><div class="stat-number" id="totalClients">0</div><div class="stat-label">Clients</div></div>
    <div class="stat-card"><div class="stat-number" id="totalRevenue">₹0</div><div class="stat-label">Revenue</div></div>
    <div class="stat-card"><div class="stat-number" id="pendingAmount">₹0</div><div class="stat-label">Pending</div></div>
    <div class="stat-card"><div class="stat-number" id="monthRevenue">₹0</div><div class="stat-label">This Month</div></div>
  </div>
  <div class="tabs">
    <button class="tab active" data-tab="clients">👥 Clients</button>
    <button class="tab" data-tab="add">➕ Add Client</button>
    <button class="tab" data-tab="reports">📊 Reports</button>
  </div>
  <div id="tabClients" class="panel active"><div id="clientsList"><div class="empty-state">Loading...</div></div></div>
  <div id="tabAdd" class="panel">
    <div class="form-card">
      <div class="form-group"><label>Client Name *</label><input type="text" id="newName"></div>
      <div class="form-group"><label>Company</label><input type="text" id="newCompany"></div>
      <div class="form-group"><label>Phone</label><input type="text" id="newPhone"></div>
      <div class="form-group"><label>Email</label><input type="email" id="newEmail"></div>
      <div class="form-group"><label>Service</label>
        <select id="serviceSelect">
          <option value="Website Development">🌐 Website Development - ₹15,000</option>
          <option value="Domain New">🔗 Domain New - ₹899</option>
          <option value="Domain Renewal">🔄 Domain Renewal - ₹899</option>
          <option value="Hosting New">🚀 Hosting New - ₹6,000</option>
          <option value="Hosting Renewal">🔄 Hosting Renewal - ₹6,000</option>
          <option value="Google Workspace">📧 Google Workspace - ₹1,200</option>
          <option value="Microsoft 365">💼 Microsoft 365 - ₹1,100</option>
          <option value="WhatsApp API">💬 WhatsApp API - ₹5,000</option>
          <option value="SMS API">📱 SMS API - ₹3,000</option>
          <option value="Annual Support">🛡️ Annual Support - ₹10,000</option>
        </select>
      </div>
      <div class="form-group"><label>Amount</label><input type="number" id="serviceAmount"></div>
      <button id="addClientBtn" class="add-btn">➕ Add Client</button>
    </div>
  </div>
  <div id="tabReports" class="panel">
    <div class="form-card"><h3>💰 This Month</h3><div id="monthSummary"></div></div>
    <div class="form-card" style="margin-top:16px"><h3>📋 Recent Payments</h3><div id="recentPayments"></div></div>
  </div>
</div>

<!-- Payment Modal -->
<div id="payModal" class="modal">
  <div class="modal-content">
    <h3 id="modalTitle">Record Payment</h3>
    <div id="modalBody"></div>
    <div class="form-group"><label>Amount</label><input type="number" id="payAmount"></div>
    <div class="form-group"><label>Mode</label>
      <select id="payMode">
        <option value="cash">💵 Cash</option>
        <option value="upi">📱 UPI</option>
        <option value="bank">🏦 Bank Transfer</option>
        <option value="card">💳 Card</option>
      </select>
    </div>
    <button id="recordPayBtn" class="add-btn" style="background:#667eea;">Record Payment</button>
    <button id="closeModal" style="background:#f1f5f9;border:none;border-radius:60px;padding:12px;margin-top:12px;width:100%;cursor:pointer;">Close</button>
  </div>
</div>

<script>
const API = '/soft/api/';

async function callApi(endpoint, data) {
    let res = await fetch(API + endpoint, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    });
    return await res.json();
}

async function loadDashboard() {
    let stats = await callApi('stats.php', {});
    if(stats.success) {
        document.getElementById('totalClients').innerText = stats.total_clients;
        document.getElementById('totalRevenue').innerHTML = '₹' + (stats.total_revenue || 0).toLocaleString();
        document.getElementById('pendingAmount').innerHTML = '₹' + (stats.pending_amount || 0).toLocaleString();
        document.getElementById('monthRevenue').innerHTML = '₹' + (stats.month_revenue || 0).toLocaleString();
        document.getElementById('monthSummary').innerHTML = `
            <div class="payment-item"><span>💰 Received This Month</span><span>₹${(stats.month_revenue || 0).toLocaleString()}</span></div>
            <div class="payment-item"><span>⏳ Total Pending</span><span>₹${(stats.pending_amount || 0).toLocaleString()}</span></div>
        `;
    }
    let clients = await callApi('clients.php', {});
    if(clients.success) renderClients(clients.clients);
}

function renderClients(clients) {
    let html = '';
    for(let c of clients) {
        html += `<div class="client-card">
            <div class="client-name">${escapeHtml(c.client_name)}</div>
            <div class="client-detail">${escapeHtml(c.company_name || '')} | ${c.phone || ''}</div>
            <div class="client-stats"><span class="paid">₹${Number(c.total_paid).toLocaleString()} Paid</span><span class="due">₹${Number(c.total_due).toLocaleString()} Due</span></div>
            <button class="btn-sm" onclick="openPayModal(${c.id}, '${escapeHtml(c.client_name)}')">💰 Record Payment</button>
        </div>`;
    }
    document.getElementById('clientsList').innerHTML = html || '<div class="empty-state">No clients yet</div>';
}

let currentClient = null;
async function openPayModal(id, name) {
    currentClient = id;
    document.getElementById('modalTitle').innerText = name;
    let clients = await callApi('clients.php', {});
    let client = clients.clients?.find(c => c.id === id);
    let payments = client?.payments || [];
    let ph = payments.map(p => `<div class="payment-item"><span>${p.payment_date}</span><span>₹${p.amount} (${p.payment_mode})</span></div>`).join('');
    document.getElementById('modalBody').innerHTML = `
        <div style="background:#f0f2f5;border-radius:16px;padding:12px;margin-bottom:16px">
            <div>Total Billed: ₹${Number(client?.amount).toLocaleString()}</div>
            <div>Total Paid: ₹${Number(client?.total_paid).toLocaleString()}</div>
            <div>Pending: ₹${Number(client?.total_due).toLocaleString()}</div>
        </div>
        <div><strong>Payments</strong></div>
        ${ph || 'No payments'}
    `;
    document.getElementById('payModal').classList.add('show');
}

document.getElementById('recordPayBtn')?.addEventListener('click', async () => {
    let amount = document.getElementById('payAmount').value;
    if(!amount) return alert('Enter amount');
    let res = await callApi('add_payment.php', { client_id: currentClient, amount, mode: document.getElementById('payMode').value });
    if(res.success) { alert('Payment recorded!'); document.getElementById('payModal').classList.remove('show'); loadDashboard(); }
    else alert('Failed');
});

document.getElementById('addClientBtn')?.addEventListener('click', async () => {
    let name = document.getElementById('newName').value.trim();
    if(!name) return alert('Enter client name');
    let res = await callApi('add_client.php', {
        name, company: document.getElementById('newCompany').value,
        phone: document.getElementById('newPhone').value, email: document.getElementById('newEmail').value,
        service_name: document.getElementById('serviceSelect').value.split(' - ')[0],
        amount: document.getElementById('serviceAmount').value
    });
    if(res.success) { alert('Client added!'); location.reload(); }
    else alert('Failed');
});

// Fingerprint
function bufToBase64(b) { let bin='', v=new Uint8Array(b); for(let i=0;i<v.length;i++) bin+=String.fromCharCode(v[i]); return btoa(bin); }
function base64ToBuf(b) { let bin=atob(b), buf=new ArrayBuffer(bin.length), v=new Uint8Array(buf); for(let i=0;i<bin.length;i++) v[i]=bin.charCodeAt(i); return buf; }

async function fingerprintLogin() {
    let username = document.getElementById('loginUser').value.trim();
    let check = await callApi('login.php', { action: 'check_fingerprint', username });
    if(!check.hasFingerprint) return showStatus('No fingerprint. Use password first.', 'error');
    try {
        let challenge = new Uint8Array(32);
        crypto.getRandomValues(challenge);
        await navigator.credentials.get({ publicKey: { challenge, allowCredentials: [{ id: base64ToBuf(check.credentialId), type: 'public-key' }], userVerification: 'required' } });
        let res = await callApi('login.php', { action: 'fingerprint_login', username, credentialId: check.credentialId });
        if(res.success) location.reload();
        else showStatus(res.message, 'error');
    } catch(e) { showStatus('Fingerprint failed', 'error'); }
}

async function passwordLogin() {
    let res = await callApi('login.php', { action: 'password_login', username: document.getElementById('loginUser').value.trim(), password: document.getElementById('loginPass').value });
    if(res.success) location.reload();
    else showStatus('Invalid credentials', 'error');
}

function logout() { location.href = '/soft/api/logout.php'; }
function showStatus(msg, type) { let el = document.getElementById('statusMsg'); el.innerHTML = msg; el.style.background = type==='error'?'#f8d7da':'#d4edda'; el.style.color = type==='error'?'#721c24':'#155724'; setTimeout(()=>el.innerHTML='',3000); }
function escapeHtml(s) { if(!s) return ''; return s.replace(/[&<>]/g, m => m==='&'?'&amp;':m==='<'?'&lt;':'&gt;'); }

// Tab switching
document.querySelectorAll('.tab').forEach(btn => {
    btn.addEventListener('click', () => {
        let tab = btn.dataset.tab;
        document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
        document.getElementById(`tab${tab.charAt(0).toUpperCase() + tab.slice(1)}`).classList.add('active');
        document.querySelectorAll('.tab').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
    });
});

// Price auto-fill
const prices = { 'Website Development':15000, 'Domain New':899, 'Domain Renewal':899, 'Hosting New':6000, 'Hosting Renewal':6000, 'Google Workspace':1200, 'Microsoft 365':1100, 'WhatsApp API':5000, 'SMS API':3000, 'Annual Support':10000 };
document.getElementById('serviceSelect')?.addEventListener('change', () => document.getElementById('serviceAmount').value = prices[document.getElementById('serviceSelect').value.split(' - ')[0]] || 0);
document.getElementById('serviceSelect')?.dispatchEvent(new Event('change'));

document.getElementById('fpLoginBtn')?.addEventListener('click', fingerprintLogin);
document.getElementById('pwLoginBtn')?.addEventListener('click', passwordLogin);
document.getElementById('logoutBtn')?.addEventListener('click', logout);
document.getElementById('closeModal')?.addEventListener('click', () => document.getElementById('payModal').classList.remove('show'));

</script>
</body>
</html>