<?php
// admin.php — Secure Admin Panel for Dashboard Data

session_start();

// ====== CONFIGURE LOGIN CREDENTIALS ======
$ADMIN_USER = "admin";
$ADMIN_PASS = "myheritage1"; // 🔒 Change this immediately for security

// ====== LOGIN HANDLER ======
if (isset($_POST['login'])) {
    if ($_POST['username'] === $ADMIN_USER && $_POST['password'] === $ADMIN_PASS) {
        $_SESSION['logged_in'] = true;
    } else {
        $error = "Invalid username or password.";
    }
}

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

// ====== IF NOT LOGGED IN ======
if (empty($_SESSION['logged_in'])):
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background: #0b5ed7; height: 100vh; display: flex; align-items: center; justify-content: center; font-family: "Segoe UI",sans-serif; }
.card { width: 360px; box-shadow: 0 0.4rem 0.8rem rgba(0,0,0,0.3); border:none; }
</style>
</head>
<body>

<div class="card p-4">
  <h4 class="text-center mb-3">Admin Login</h4>
  <?php if (!empty($error)): ?>
    <div class="alert alert-danger py-2"><?=$error?></div>
  <?php endif; ?>
  <form method="post">
    <div class="mb-3">
      <label class="form-label">Username</label>
      <input type="text" name="username" class="form-control" required>
    </div>
    <div class="mb-3">
      <label class="form-label">Password</label>
      <input type="password" name="password" class="form-control" required>
    </div>
    <div class="d-grid">
      <button type="submit" name="login" class="btn btn-primary">Login</button>
    </div>
  </form>
</div>

</body>
</html>
<?php
exit;
endif;

// ====== ADMIN PANEL SECTION ======
$dataFile = __DIR__ . '/data.json';
if (!file_exists($dataFile)) die("❌ data.json not found.");



$data = json_decode(file_get_contents($dataFile), true);
if (!$data) die("❌ Invalid data.json format.");


function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Handles cases behind proxies or load balancers
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_data'])) {
    $data['account'] = [
        'owner' => $_POST['owner'],
        'account_number' => $_POST['account_number'],
        'balance' => floatval($_POST['balance']),
        'linked_cards' => intval($_POST['linked_cards']),
        'fico_score' => intval($_POST['fico_score']),
        'ip_address' => getUserIP(),
        'profile_pic' => $_POST['profile_pic'],
        'income_percentage' => floatval($_POST['income_percentage']),
        'debit_percentage' => floatval($_POST['debit_percentage']),
        'business_support_loan' => [
            'amount' => floatval($_POST['loan_amount']),
            'status' => $_POST['loan_status'],
            'interest_rate' => floatval($_POST['loan_interest_rate']),
        ],
    ];

    $transactions = json_decode($_POST['transactions_json'], true);
    if (is_array($transactions)) {
        $data['transactions'] = $transactions;
    }

    file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT));
    $saved = true;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Panel — Manage Dashboard Data</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background:#f8f9fa; padding:40px; font-family: "Segoe UI",sans-serif; }
textarea { font-family: monospace; white-space: pre; }
.card { box-shadow: 0 0.25rem 0.5rem rgba(0,0,0,0.1); border:none; }
</style>
</head>
<body>

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>🛠 Admin Panel — Manage Dashboard Data</h2>
        <a href="?logout=1" class="btn btn-outline-danger btn-sm">Logout</a>
    </div>

    <?php if (!empty($saved)): ?>
      <div class="alert alert-success">✅ Changes saved successfully!</div>
    <?php endif; ?>

    <form method="post">
        <input type="hidden" name="save_data" value="1">

        <div class="card mb-4">
            <div class="card-header bg-primary text-white">Account Information</div>
            <div class="card-body row g-3">
                <div class="col-md-6">
                    <label class="form-label">Owner</label>
                    <input type="text" name="owner" value="<?=htmlspecialchars($data['account']['owner'])?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Account Number</label>
                    <input type="text" name="account_number" value="<?=htmlspecialchars($data['account']['account_number'])?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Balance ($)</label>
                    <input type="number" step="0.01" name="balance" value="<?=$data['account']['balance']?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Linked Cards</label>
                    <input type="number" name="linked_cards" value="<?=$data['account']['linked_cards']?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">FICO Score</label>
                    <input type="number" name="fico_score" value="<?=$data['account']['fico_score']?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">IP Address</label>
                    <input type="text" name="ip_address" value="<?=htmlspecialchars($data['account']['ip_address'])?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Profile Picture URL</label>
                    <input type="text" name="profile_pic" value="<?=htmlspecialchars($data['account']['profile_pic'])?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Income %</label>
                    <input type="number" step="0.1" name="income_percentage" value="<?=$data['account']['income_percentage']?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Debit %</label>
                    <input type="number" step="0.1" name="debit_percentage" value="<?=$data['account']['debit_percentage']?>" class="form-control">
                </div>
                <h6 class="mt-4">Business Support Loan</h6>
                <div class="col-md-4">
                    <label class="form-label">Loan Amount</label>
                    <input type="number" step="0.01" name="loan_amount" value="<?=$data['account']['business_support_loan']['amount']?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Status</label>
                    <input type="text" name="loan_status" value="<?=htmlspecialchars($data['account']['business_support_loan']['status'])?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Interest Rate %</label>
                    <input type="number" step="0.1" name="loan_interest_rate" value="<?=$data['account']['business_support_loan']['interest_rate']?>" class="form-control">
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header bg-success text-white">Transactions</div>
            <div class="card-body">
                <p class="text-muted small mb-2">Edit transactions as JSON array:</p>
                <textarea name="transactions_json" rows="12" class="form-control"><?=htmlspecialchars(json_encode($data['transactions'], JSON_PRETTY_PRINT))?></textarea>
                <small class="text-muted">Each transaction should have: date, description, category, type, status, reference, amount</small>
            </div>
        </div>

        <div class="d-grid">
            <button type="submit" class="btn btn-primary btn-lg">💾 Save Changes</button>
        </div>
    </form>
</div>

</body>
</html>
