<?php
// index.php - Simple Banking Dashboard (PHP + HTML + CSS + JS)
// Usage: put this file in a PHP-enabled server (e.g., XAMPP, MAMP, LAMP) inside a folder.
// The script will create a data.json file in the same directory to persist data.
// NOTE: This is a demo/prototype. Do not use in production without proper security.

// Path to data file
$dataFile = __DIR__ . '/data.json';

// Initialize default data if file doesn't exist
$defaultData = [
    'account' => [
        'owner' => 'Courtney Rice',
        'account_number' => '2238 6254 9466 002',
        'profile_pic' => 'profile.png',
        'balance' => 2350000.00
    ],
    'transactions' => [
        [
            'id' => uniqid(),
            'date' => date('c', strtotime('-30 days')),
            'type' => 'credit',
            'amount' => 1200000.00,
            'description' => 'Credit(1529)',
        ],
        [
            'id' => uniqid(),
            'date' => date('c', strtotime('-25 days')),
            'type' => 'credit',
            'amount' => 15000.00,
            'description' => 'Credit(1528)',
        ],
        [
            'id' => uniqid(),
            'date' => date('c', strtotime('-10 days')),
            'type' => 'debit',
            'amount' => 5000.00,
            'description' => 'Transfer(6334) - Debit',
        ],
        [
            'id' => uniqid(),
            'date' => date('c', strtotime('-5 days')),
            'type' => 'debit',
            'amount' => 45000.00,
            'description' => 'Transfer(6333) - Debit',
        ],
        [
            'id' => uniqid(),
            'date' => date('c', strtotime('-2 days')),
            'type' => 'debit',
            'amount' => 250.00,
            'description' => 'Transfer(6332) - Debit',
        ],
    ],
];

// Create data file if missing
if (!file_exists($dataFile)) {
    file_put_contents($dataFile, json_encode($defaultData, JSON_PRETTY_PRINT));
}

// Load data
    // reload to reflect changes
    $raw = file_get_contents($dataFile);
    $data = json_decode($raw, true);


if (!$data) {
    $data = $defaultData;
}

// Helper: save data
function save_data($data, $file) {
    // basic locking
    $tmp = tmpfile();
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
}

// Handle POST: sending money or adding income (two-action demo)
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // simple action switch
    $action = $_POST['action'] ?? '';
    if ($action === 'send') {
        $recipient_name = trim($_POST['recipient_name'] ?? '');
        $recipient_account = trim($_POST['recipient_account'] ?? '');
        $amount = floatval($_POST['amount'] ?? 0);
        $note = trim($_POST['note'] ?? '');

        if ($amount <= 0) {
            $message = 'Amount must be greater than 0.';
        } elseif ($amount > $data['account']['balance']) {
            $message = 'Insufficient funds.';
        } elseif (empty($recipient_name) || empty($recipient_account)) {
            $message = 'Please provide recipient name and account number.';
        } else {
            // Deduct balance
            $data['account']['balance'] -= $amount;
            // Create transaction
            $txn = [
                'id' => uniqid(),
                'date' => date('c'),
                'type' => 'debit',
                'amount' => $amount,
                'description' => 'Sent to ' . $recipient_name . ' (' . $recipient_account . ')' . ($note ? ' - ' . $note : ''),
            ];
            array_unshift($data['transactions'], $txn); // most recent first
            save_data($data, $dataFile);
            $message = 'Money sent successfully.';
        }
    } elseif ($action === 'add_income') {
        $amount = floatval($_POST['income_amount'] ?? 0);
        $description = trim($_POST['income_description'] ?? 'Income');
        if ($amount <= 0) {
            $message = 'Income amount must be greater than 0.';
        } else {
            $data['account']['balance'] += $amount;
            $txn = [
                'id' => uniqid(),
                'date' => date('c'),
                'type' => 'credit',
                'amount' => $amount,
                'description' => $description,
            ];
            array_unshift($data['transactions'], $txn);
            save_data($data, $dataFile);
            $message = 'Income added.';
        }
    }
    // reload to reflect changes
    $raw = file_get_contents($dataFile);
    $data = json_decode($raw, true);
}

// Prepare quick stats for the last 30 days: sum income & loss
$now = new DateTime();
$income = 0.0;
$loss = 0.0;
foreach ($data['transactions'] as $t) {
    $tDate = new DateTime($t['date']);
    $diff = $now->diff($tDate)->days;
    if ($diff <= 30) {
        if ($t['type'] === 'credit') $income += $t['amount'];
        else $loss += $t['amount'];
    }
}

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Banking Dashboard — First Heritage Bank</title>
    <style>
        /* Simple responsive CSS - professional look */
        :root{--bg:#f5f7fb;--card:#ffffff;--muted:#6b7280;--accent:#0d8abc;--danger:#ef4444;}
        *{box-sizing:border-box}
        body{margin:0;font-family:Inter,ui-sans-serif,system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial;background:var(--bg);color:#111}
        .container{max-width:1100px;margin:28px auto;padding:18px}
        .grid{display:grid;grid-template-columns:1fr 360px;gap:18px}
        @media (max-width:900px){.grid{grid-template-columns:1fr} .right-col{order:-1}}
        .card{background:var(--card);border-radius:12px;padding:18px;box-shadow:0 6px 18px rgba(16,24,40,0.06)}
        .header{display:flex;align-items:center;gap:12px}
        .profile-pic{width:64px;height:64px;border-radius:50%;overflow:hidden}
        .h1{font-size:18px;font-weight:600}
        .muted{color:var(--muted);font-size:13px}
        .balance{font-size:28px;font-weight:700;margin-top:6px}
        .actions{display:flex;gap:8px;margin-top:12px}
        .btn{padding:10px 12px;border-radius:10px;border:none;cursor:pointer;font-weight:600}
        .btn-primary{background:var(--accent);color:#fff}
        .btn-outline{background:transparent;border:1px solid #e6eef6;color:var(--accent)}
        .small{font-size:13px}
        .summary{display:flex;gap:12px;margin-top:12px}
        .summary .item{flex:1;padding:12px;border-radius:10px;background:linear-gradient(180deg,#fff,#5792e1);text-align:center}
        .transactions{margin-top:12px}
        .txn{display:flex;justify-content:space-between;align-items:center;padding:10px 12px;border-radius:10px;border:1px solid #f0f4f8;margin-bottom:8px}
        .txn .left{display:flex;gap:12px;align-items:center}
        .badge-credit{color:green}
        .badge-debit{color:var(--danger)}
        .form-row{display:flex;gap:8px}
        input,select,textarea{padding:10px;border-radius:8px;border:1px solid #e6eef6;width:100;font-size:14px}
        label{font-size:13px;color:var(--muted);display:block;margin-bottom:6px}
        .right-sticky{position:sticky;top:18px}
        .chart-wrap{height:220px}
        .footer-note{font-size:12px;color:var(--muted);margin-top:10px}
    </style>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <!-- Top Menu Bar -->
<div class="top-menu">
    <div class="menu-left">
        <img src="logo.png" alt="Logo" class="logo">
    </div>
    <div class="menu-right">
        <span class="contact-info">📧 contact@firstheritageus.com</span>
        <a href="" class="dashboard-link">User Dashboard</a>
    </div>
</div>
<style>
    /* === RESPONSIVENESS FIXES === */

/* Make top menu stack and scale */
@media (max-width: 768px) {
    
    .grid{display:block;grid-template-columns:1fr 360px;gap:18px}
    
  .top-menu {
    flex-direction: column;
    align-items: flex-start;
    padding: 12px;
    gap: 6px;
  }
  .menu-right {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  .contact-info {
    font-size: 13px;
    word-break: break-word;
  }
  .dashboard-link {
    font-size: 14px;
  }
}

/* Main grid adjustment for smaller viewports */
@media (max-width: 900px) {
    .grid{display:block;grid-template-columns:1fr 360px;gap:18px}
  .grid {
    grid-template-columns: 1fr;
  }
  .right-col {
    order: -1;
  }
  .right-sticky {
    position: static;
  }
}

/* Cards and text adjustments for mobile */
@media (max-width: 600px) {
    .grid{display:block;grid-template-columns:1fr 360px;gap:18px}
  .container {
    padding: 10px;
  }

  .card {
    padding: 14px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .profile-pic {
    width: 56px;
    height: 56px;
  }

  .balance {
    font-size: 22px;
  }

  .summary {
    flex-direction: column;
  }

  .summary .item {
    text-align: left;
  }

  .actions {
    flex-direction: column;
    width: 100%;
  }

  .btn {
    width: 100%;
  }

  .transactions .txn {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .txn .left {
    width: 100%;
  }

  .chart-wrap {
    height: 180px !important;
  }

  input, select, textarea {
    font-size: 15px;
  }

  .muted.small, .footer-note {
    font-size: 12px;
  }
}

/* Make tables and content never overflow */
html, body {
  overflow-x: hidden;
}

    /* ===== Top Menu Bar ===== */
.top-menu {
    width: 100%;
    background: var(--card);
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    padding: 10px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 100;
}

.top-menu .logo {
    height: 40px;
    width: auto;
}

.menu-right {
    display: flex;
    align-items: center;
    gap: 20px;
}

.contact-info {
    font-size: 14px;
    color: var(--muted);
}

.dashboard-link {
    font-weight: 600;
    color: var(--accent);
    text-decoration: none;
    transition: color 0.2s ease;
}

.dashboard-link:hover {
    color: #0b6c9c;
}

</style>
<div class="container">
    
    <div class="grid">
        <main>
            <div class="card">
                <div class="header">
                    <div class="profile-pic"><img src="<?php echo htmlspecialchars($data['account']['profile_pic']); ?>" alt="profile" style="width:100%;height:100%"></div>
                    <div>
                        <div class="h1"><?php echo htmlspecialchars($data['account']['owner']); ?></div>
                        <div class="muted">Account: <?php echo htmlspecialchars($data['account']['account_number']); ?></div>
                        <div class="balance"><?php echo '$ ' . number_format($data['account']['balance'], 2, '.', ','); ?></div>
                    </div>
                    <div style="margin-left:auto;text-align:right">
                        <div class="muted small">Last 30 days</div>
                        <div class="small">Income: <?php echo '$ ' . number_format($income,2,'.',','); ?> / Loss: <?php echo '$ ' . number_format($loss,2,'.',','); ?></div>
                    </div>
                </div>
                
                <div style="text-align:right; margin-top:10px;">
    <form method="post" action="logout.php">
        <button class="btn btn-outline" type="submit">Logout</button>
    </form>
</div>


                <div class="summary">
                    <div class="item">
                        <div class="muted small">Current Balance</div>
                        <div style="font-weight:700;font-size:20px;margin-top:6px"><?php echo '$ ' . number_format($data['account']['balance'],2,'.',','); ?></div>
                    </div>
                    <div class="item">
                        <div class="muted small">Total Income (30d)</div>
                        <div style="font-weight:700;font-size:20px;margin-top:6px"><?php echo '$ ' . number_format($income,2,'.',','); ?></div>
                    </div>
                    <div class="item">
                        <div class="muted small">Total Loss (30d)</div>
                        <div style="font-weight:700;font-size:20px;margin-top:6px"><?php echo '$ ' . number_format($loss,2,'.',','); ?></div>
                    </div>
                </div>

                <div style="margin-top:16px;display:flex;align-items:center;justify-content:space-between">
                    <div class="muted">Transaction History</div>
                    <div class="muted small">Showing recent transactions</div>
                </div>

                <div class="transactions">
                    <?php foreach ($data['transactions'] as $t): ?>
                        <div class="txn">
                            <div class="left">
                                <div style="width:44px;height:44px;border-radius:10px;background:#f3f7fb;display:flex;align-items:center;justify-content:center;font-weight:700"><?php echo ($t['type']==='credit')?'+':'-'; ?></div>
                                <div>
                                    <div style="font-weight:700"><?php echo htmlspecialchars($t['description']); ?></div>
                                    <div class="muted small"><?php echo (new DateTime($t['date']))->format('Y-m-d H:i'); ?></div>
                                </div>
                            </div>
                            <div style="text-align:right">
                                <div style="font-weight:700;" class="<?php echo ($t['type']==='credit')? 'badge-credit':'badge-debit'; ?>"><?php echo ($t['type']==='credit'? '+ ':'- '); ?><?php echo '$ ' . number_format($t['amount'],2,'.',','); ?></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

            </div>

            <div style="height:16px"></div>

            <div class="card">
                <div style="display:flex;align-items:center;justify-content:space-between">
                    <div class="h1">Overview chart</div>
                    <div class="muted small">Last 30 days</div>
                </div>
                <div class="chart-wrap"><canvas id="overviewChart" width="400" height="200"></canvas></div>
                <div class="footer-note">This chart shows daily net movement (credits minus debits) for the last 30 days.</div>
            </div>
            
            <br>
            <br>

        </main>

        <aside class="right-col">
            <div class="right-sticky">
                <div class="card">
                    <div class="h1">Send Money</div>
                    <?php if ($message): ?><div style="margin-top:8px;padding:10px;border-radius:8px;background:#eef7ff;color:#073d6b;font-weight:600"><?php echo htmlspecialchars($message); ?></div><?php endif; ?>
                    <form method="post" style="margin-top:12px">
                        <input type="hidden" name="action" value="send">
                        <label>Recipient name</label>
                        <input name="recipient_name" required>
                        <label style="margin-top:8px">Recipient account number</label>
                        <input name="recipient_account" required>
                        <label style="margin-top:8px">Amount (USD)</label>
                        <input name="amount" type="number" step="0.01" required>
                        <label style="margin-top:8px">Note (optional)</label>
                        <input name="note">
                        <div style="margin-top:12px;display:flex;gap:8px">
                            <button class="btn btn-primary" type="submit">Send</button>
                            <button class="btn btn-outline" type="reset">Reset</button>
                        </div>
                    </form>
                </div>

                <div style="height:12px"></div>

                <div style="display:none;" class="card">
                    <div class="h1">Quick actions</div>
                    <div style="margin-top:10px;display:flex;gap:8px">
                        <form method="post" style="flex:1">
                            <input type="hidden" name="action" value="add_income">
                            <input type="hidden" name="income_amount" value="1000">
                            <input type="hidden" name="income_description" value="Manual top-up">
                            <button class="btn btn-primary small" type="submit" style="width:100%">Add $1000 (demo)</button>
                        </form>
                        <button class="btn" onclick="document.getElementById('filterModal').style.display='block'">Filter</button>
                    </div>
                    <div class="footer-note" style="margin-top:10px">Demo buttons modify local server data.json file.</div>
                </div>

                <div style="height:12px"></div>

                <div class="card">
                    <div class="h1">Account details</div>
                    <div class="muted small" style="margin-top:8px">Owner</div>
                    <div style="font-weight:700;margin-top:6px"><?php echo htmlspecialchars($data['account']['owner']); ?></div>
                    <div class="muted small" style="margin-top:8px">Account number</div>
                    <div style="font-weight:700;margin-top:6px"><?php echo htmlspecialchars($data['account']['account_number']); ?></div>
                </div>
            </div>
        </aside>
    </div>
</div>

<!-- Simple modal (hidden) for potential filters (demo) -->
<div id="filterModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.4);align-items:center;justify-content:center">
    <div style="width:90%;max-width:520px;background:#fff;padding:18px;border-radius:12px;margin:auto">
        <div style="display:flex;justify-content:space-between;align-items:center">
            <div class="h1">Filter transactions</div>
            <button onclick="document.getElementById('filterModal').style.display='none'">Close</button>
        </div>
        <p class="muted">This is a demo filter placeholder.</p>
    </div>
</div>

<script>
// Prepare chart data from PHP echoing JSON
const transactions = <?php echo json_encode($data['transactions']); ?>;

// Build last 30 days labels and net values per day
const DAYS = 30;
const labels = [];
const net = [];
const dayMap = {};
for (let i = DAYS-1; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    const key = d.toISOString().slice(0,10);
    labels.push(key);
    dayMap[key] = 0;
}

transactions.forEach(t => {
    const d = new Date(t.date);
    const key = d.toISOString().slice(0,10);
    if (key in dayMap) {
        if (t.type === 'credit') dayMap[key] += Number(t.amount);
        else dayMap[key] -= Number(t.amount);
    }
});

labels.forEach(l => net.push(Math.round((dayMap[l] + Number.EPSILON) * 100)/100));

const ctx = document.getElementById('overviewChart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: [{
            label: 'Net movement ($)',
            data: net,
            borderWidth: 1
        }]
    },
    options: {
        responsive:true,
        maintainAspectRatio: false,
        scales: {
            x: { display: false },
            y: { beginAtZero: true }
        }
    }
});
</script>
</body>
</html>
