<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];
$success = '';
$error = '';

// Handle Profile Updates
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_profile'])) {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        
        if (empty($name) || empty($email)) {
            $error = "Name and Email are required.";
        } else {
            try {
                // Check if email is already taken
                $check = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
                $check->execute([$email, $user_id]);
                if ($check->fetch()) {
                    $error = "This email is already registered.";
                } else {
                    // Handle Profile Picture
                    $profile_pic = null;
                    if (!empty($_FILES['profile_pic']['name']) && $_FILES['profile_pic']['error'] === 0) {
                        $ext = strtolower(pathinfo($_FILES['profile_pic']['name'], PATHINFO_EXTENSION));
                        if (in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp'])) {
                            $avatar_dir = 'assets/images/avatars/';
                            if (!is_dir(__DIR__ . '/' . $avatar_dir)) {
                                mkdir(__DIR__ . '/' . $avatar_dir, 0777, true);
                            }
                            $newName = $avatar_dir . 'avatar_' . $user_id . '_' . time() . '.' . $ext;
                            if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], __DIR__ . '/' . $newName)) {
                                $profile_pic = $newName;
                            }
                        }
                    }

                    if ($profile_pic) {
                        $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, phone = ?, profile_pic = ? WHERE id = ?");
                        $params = [$name, $email, $phone, $profile_pic, $user_id];
                    } else {
                        $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, phone = ? WHERE id = ?");
                        $params = [$name, $email, $phone, $user_id];
                    }

                    if ($stmt->execute($params)) {
                        $success = "Profile updated successfully!";
                        $_SESSION['user_name'] = $name;
                    }
                }
            } catch (PDOException $e) { $error = "Update error."; }
        }
    }

    // Handle Password Update
    if (isset($_POST['update_password'])) {
        $current_pw = $_POST['current_password'] ?? '';
        $new_pw = $_POST['new_password'] ?? '';
        $confirm_pw = $_POST['confirm_password'] ?? '';

        if (empty($current_pw) || empty($new_pw)) {
            $error = "All password fields are required.";
        } elseif ($new_pw !== $confirm_pw) {
            $error = "Passwords do not match.";
        } else {
            try {
                $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $user_pw = $stmt->fetchColumn();

                if (password_verify($current_pw, $user_pw)) {
                    $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                    $stmt->execute([password_hash($new_pw, PASSWORD_DEFAULT), $user_id]);
                    $success = "Password securely updated!";
                } else { $error = "Current password incorrect."; }
            } catch (PDOException $e) { $error = "Security update failed."; }
        }
    }
}

// Fetch Comprehensive Statistics
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    $site_settings = get_site_settings($pdo);
    $system_comm = $site_settings['system_commission'] ?? 0;

    // 1. Available Balance
    $stmt = $pdo->prepare("SELECT SUM(t.amount) as gross_earned FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ? AND t.status = 'completed'");
    $stmt->execute([$user_id]);
    $gross_earned = $stmt->fetch()['gross_earned'] ?? 0;
    
    $total_earned = $gross_earned * (1 - ($system_comm / 100));

    $stmt = $pdo->prepare("SELECT SUM(amount) as withdrawn FROM withdrawals WHERE user_id = ? AND status IN ('completed', 'pending')");
    $stmt->execute([$user_id]);
    $total_withdrawn_all = $stmt->fetch()['withdrawn'] ?? 0;

    $available_balance = $total_earned - $total_withdrawn_all;

    // 2. Transaction Summary
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ? AND t.status = 'completed'");
    $stmt->execute([$user_id]);
    $completed_transactions = $stmt->fetchColumn() ?: 0;

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ? AND t.status = 'pending'");
    $stmt->execute([$user_id]);
    $pending_transactions = $stmt->fetchColumn() ?: 0;

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ?");
    $stmt->execute([$user_id]);
    $total_transactions = $stmt->fetchColumn() ?: 0;

    // 3. Withdrawal Summary
    $stmt = $pdo->prepare("SELECT SUM(amount) as paid FROM withdrawals WHERE user_id = ? AND status = 'completed'");
    $stmt->execute([$user_id]);
    $total_withdrawals = $stmt->fetch()['paid'] ?? 0;

    $stmt = $pdo->prepare("SELECT SUM(amount) as pending FROM withdrawals WHERE user_id = ? AND status = 'pending'");
    $stmt->execute([$user_id]);
    $pending_withdrawals = $stmt->fetch()['pending'] ?? 0;

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM withdrawals WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $withdrawal_requests = $stmt->fetchColumn() ?: 0;

} catch (PDOException $e) { $error = "Failed to load dashboard data."; }

$pageTitle = "Account Settings - SonicPesa";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    :root {
        --bf-green: #D9F7EF;
        --bf-blue: #e0e7ff;
        --bf-yellow: #fef3c7;
        --bf-gray: #f3f4f6;
        --bf-accent: #6366f1;
    }
    .profile-card-modern {
        background: white; border-radius: 24px; border: 1px solid rgba(0,0,0,0.05);
        box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden;
    }
    .profile-banner {
        height: 120px; background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
        opacity: 0.9;
    }
    .profile-img-wrap {
        margin-top: -60px; position: relative; display: inline-block;
    }
    .profile-avatar {
        width: 120px; height: 120px; border-radius: 50%;
        border: 6px solid white; background: #fff; object-fit: cover;
        box-shadow: 0 8px 16px rgba(0,0,0,0.08);
    }
    .avatar-placeholder {
        background: #fdfdfd; color: var(--bf-accent); font-size: 40px;
        display: flex; align-items: center; justify-content: center;
    }
    .glass-api-card {
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(99, 102, 241, 0.1);
        border-radius: 20px;
        padding: 32px;
        box-shadow: 0 8px 32px rgba(99, 102, 241, 0.05);
    }
    .api-key-container {
        background: linear-gradient(90deg, #f8fafc 0%, #f1f5f9 100%);
        border: 1.5px dashed rgba(99, 102, 241, 0.2);
        padding: 16px 24px;
        border-radius: 12px;
        display: flex; align-items: center; justify-content: space-between;
    }
    .stat-card-lite {
        padding: 24px; border-radius: 20px; border: 0;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        height: 100%; display: flex; flex-direction: column; justify-content: center;
    }
    .stat-card-lite:hover { transform: translateY(-5px); box-shadow: 0 12px 24px rgba(0,0,0,0.05); }
    .metric-value { font-size: 24px; font-weight: 800; color: #1e293b; margin-bottom: 4px; }
    .metric-label { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; }
</style>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <!-- Header Section -->
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-32">
                <div>
                    <h4 class="fw-bold mb-4">Account Overview</h4>
                    <p class="text-secondary-light text-sm mb-0">Manage your profile, security, and developer settings.</p>
                </div>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-primary radius-12 px-24 py-12 d-flex align-items-center gap-2 shadow-sm" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                        <iconify-icon icon="solar:user-edit-bold-duotone" class="text-xl"></iconify-icon>
                        <span class="fw-bold">Edit Details</span>
                    </button>
                    <button type="button" class="btn btn-outline-dark radius-12 px-24 py-12 d-flex align-items-center gap-2" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
                        <iconify-icon icon="solar:lock-password-bold-duotone" class="text-xl"></iconify-icon>
                        <span class="fw-bold">Security</span>
                    </button>
                </div>
            </div>

            <?php if($success || $error): ?>
                <div class="alert <?= $success ? 'alert-success border-success-100 bg-success-50 text-success-main' : 'alert-danger border-danger-100 bg-danger-50 text-danger-main' ?> alert-dismissible fade show radius-16 p-16 mb-32 border-2" role="alert">
                    <div class="d-flex align-items-center gap-12">
                        <iconify-icon icon="<?= $success ? 'solar:check-circle-bold' : 'solar:danger-bold' ?>" class="text-2xl"></iconify-icon>
                        <span class="fw-bold"><?= $success ?: $error ?></span>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="row gy-4">
                <!-- Profile Identity Card -->
                <div class="col-lg-4">
                    <div class="profile-card-modern h-100 p-0 text-center">
                        <div class="profile-banner"></div>
                        <div class="px-24 pb-32">
                            <div class="profile-img-wrap">
                                <?php if($user['profile_pic']): ?>
                                    <img src="<?= htmlspecialchars($user['profile_pic']) ?>" alt="Avatar" class="profile-avatar">
                                <?php else: ?>
                                    <div class="profile-avatar avatar-placeholder fw-bold">
                                        <?= strtoupper(substr($user['name'], 0, 1)) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <h4 class="mt-20 mb-4 fw-bold text-dark"><?= htmlspecialchars($user['name']) ?></h4>
                            <span class="badge bg-primary-100 text-primary-600 px-12 py-6 radius-8 fw-bold text-xs mb-24">
                                VERIFIED ACCOUNT
                            </span>

                            <div class="d-flex flex-column gap-16 text-start">
                                <div class="d-flex justify-content-between border-bottom pb-12">
                                    <span class="text-secondary-light text-xs fw-bold">ID</span>
                                    <span class="fw-bold text-dark">#<?= str_pad($user['id'], 6, '0', STR_PAD_LEFT) ?></span>
                                </div>
                                <div class="d-flex justify-content-between border-bottom pb-12">
                                    <span class="text-secondary-light text-xs fw-bold">EMAIL</span>
                                    <span class="fw-bold text-dark text-truncate" style="max-width: 180px;"><?= htmlspecialchars($user['email']) ?></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span class="text-secondary-light text-xs fw-bold">PHONE</span>
                                    <span class="fw-bold text-dark"><?= htmlspecialchars($user['phone'] ?: 'NOT SET') ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Metrics Section -->
                <div class="col-lg-8">
                    <div class="row g-4 mb-24">
                        <!-- Account Statistics -->
                        <div class="col-12"><h6 class="fw-bold mb-0 opacity-75">Account Statistics</h6></div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite" style="background: var(--bf-green);">
                                <div class="metric-value">TZS <?= number_format($available_balance) ?></div>
                                <div class="metric-label">Available Balance</div>
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite" style="background: var(--bf-blue);">
                                <div class="metric-value">TZS <?= number_format($total_earned) ?></div>
                                <div class="metric-label">Total Earnings</div>
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite" style="background: var(--bf-yellow);">
                                <div class="metric-value"><?= number_format($total_transactions) ?></div>
                                <div class="metric-label">Total Transactions</div>
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite" style="background: var(--bf-gray);">
                                <div class="metric-value"><?= number_format($withdrawal_requests) ?></div>
                                <div class="metric-label">Withdrawal Requests</div>
                            </div>
                        </div>

                        <!-- Transaction Summary -->
                        <div class="col-12 pt-16"><h6 class="fw-bold mb-0 opacity-75">Transaction Details</h6></div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite bg-white border">
                                <div class="metric-value text-primary-600"><?= number_format($completed_transactions) ?></div>
                                <div class="metric-label text-primary-400">Completed Transactions</div>
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite bg-white border">
                                <div class="metric-value text-warning-600"><?= number_format($pending_transactions) ?></div>
                                <div class="metric-label text-warning-400">Pending Transactions</div>
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite bg-white border">
                                <div class="metric-value text-success-600">TZS <?= number_format($total_withdrawals) ?></div>
                                <div class="metric-label text-success-400">Total Withdrawals</div>
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-3">
                            <div class="stat-card-lite bg-white border">
                                <div class="metric-value text-secondary-600">TZS <?= number_format($pending_withdrawals) ?></div>
                                <div class="metric-label text-secondary-400">Pending Withdrawals</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- API Access - Modern Light UI -->
                <div class="col-12">
                   <div class="glass-api-card d-flex flex-wrap align-items-center justify-content-between gap-4">
                       <div class="d-flex align-items-center gap-20">
                           <div class="w-64-px h-64-px radius-16 d-flex justify-content-center align-items-center" style="background: rgba(99, 102, 241, 0.1);">
                               <iconify-icon icon="solar:link-circle-bold-duotone" class="text-4xl text-primary-600"></iconify-icon>
                           </div>
                           <div>
                               <h5 class="fw-bold text-dark mb-4">Merchant API Credentials</h5>
                               <p class="text-secondary-light text-sm mb-0 fw-medium">Connect your store and automate video sales via our high-speed API.</p>
                           </div>
                       </div>
                       <div class="api-key-container flex-grow-1 flex-md-grow-0" style="min-width: 320px;">
                           <div class="d-flex flex-column">
                               <span class="text-xxs fw-extrabold text-primary-600 text-uppercase mb-4">Secret Key</span>
                               <code class="text-dark fw-bold text-sm" id="apiKeyDisplay"><?= $user['api_key'] ?: 'NOT_GENERATED' ?></code>
                           </div>
                           <button class="btn btn-primary btn-sm radius-8 px-16 ms-24 fw-bold" onclick="copyApiKey()">
                               <iconify-icon icon="solar:copy-bold" class="text-lg"></iconify-icon>
                               Copy
                           </button>
                       </div>
                   </div>
                </div>

                <!-- Earnings Quick Link -->
                <div class="col-12 mt-32">
                    <div class="profile-card-modern p-32 d-flex align-items-center justify-content-between flex-wrap gap-4" style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);">
                        <div class="d-flex align-items-center gap-24">
                            <div class="w-64-px h-64-px radius-16 bg-primary-100 text-primary-600 d-flex justify-content-center align-items-center text-3xl">
                                <iconify-icon icon="solar:wallet-money-bold-duotone"></iconify-icon>
                            </div>
                            <div>
                                <h5 class="fw-bold text-dark mb-4">Detailed Earnings History</h5>
                                <p class="text-secondary-light text-sm mb-0">View your comprehensive financial records, weekly/monthly summaries, and paginated reports.</p>
                            </div>
                        </div>
                        <a href="earnings.php" class="btn btn-primary radius-12 px-32 py-16 fw-bold d-flex align-items-center gap-2 shadow-sm">
                            <span class="text-lg">View My Earnings</span>
                            <iconify-icon icon="solar:arrow-right-bold" class="text-xl"></iconify-icon>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Edit Profile Modal -->
        <div class="modal fade" id="editProfileModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content radius-24 border-0">
                    <div class="modal-header py-24 px-32 border-0">
                        <h5 class="modal-title fw-bold">Edit Profile</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <div class="modal-body px-32 pb-32">
                            <div class="text-center mb-32">
                                <div class="profile-img-wrap">
                                    <img src="<?= $user['profile_pic'] ?: 'assets/images/user.png' ?>" id="upPreview" class="profile-avatar" style="width: 100px; height: 100px;">
                                    <label for="pPic" class="position-absolute bottom-0 end-0 bg-primary text-white w-32-px h-32-px radius-circle d-flex justify-content-center align-items-center cursor-pointer border border-4 border-white">
                                        <iconify-icon icon="solar:camera-add-bold" width="16"></iconify-icon>
                                    </label>
                                    <input type="file" name="profile_pic" id="pPic" class="d-none" onchange="previewAvatar(this)">
                                </div>
                            </div>
                            <div class="mb-20">
                                <label class="form-label text-sm fw-bold">Full Name</label>
                                <input type="text" name="name" class="form-control radius-12 p-12 bg-light border-0" value="<?= htmlspecialchars($user['name']) ?>" required>
                            </div>
                            <div class="mb-20">
                                <label class="form-label text-sm fw-bold">Email Address</label>
                                <input type="email" name="email" class="form-control radius-12 p-12 bg-light border-0" value="<?= htmlspecialchars($user['email']) ?>" required>
                            </div>
                            <div class="mb-0">
                                <label class="form-label text-sm fw-bold">Mobile Number</label>
                                <input type="text" name="phone" class="form-control radius-12 p-12 bg-light border-0" value="<?= htmlspecialchars($user['phone'] ?: '') ?>" placeholder="255XXXXXXXXX">
                            </div>
                        </div>
                        <div class="modal-footer border-0 px-32 pb-32">
                            <button type="submit" name="update_profile" class="btn btn-primary w-100 radius-12 py-12 fw-bold">Save All Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Change Password Modal -->
        <div class="modal fade" id="changePasswordModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content radius-24 border-0">
                    <div class="modal-header py-24 px-32 border-0">
                        <h5 class="modal-title fw-bold">Security Settings</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form method="POST">
                        <div class="modal-body px-32 pb-32">
                            <div class="mb-20">
                                <label class="form-label text-sm fw-bold">Current Password</label>
                                <input type="password" name="current_password" class="form-control radius-12 p-12 bg-light border-0" required>
                            </div>
                            <div class="mb-20">
                                <label class="form-label text-sm fw-bold">New Secure Password</label>
                                <input type="password" name="new_password" class="form-control radius-12 p-12 bg-light border-0" required>
                            </div>
                            <div class="mb-0">
                                <label class="form-label text-sm fw-bold">Confirm New Password</label>
                                <input type="password" name="confirm_password" class="form-control radius-12 p-12 bg-light border-0" required>
                            </div>
                        </div>
                        <div class="modal-footer border-0 px-32 pb-32">
                            <button type="submit" name="update_password" class="btn btn-dark w-100 radius-12 py-12 fw-bold">Update Account Security</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>

    <script>
        function copyApiKey() {
            const t = document.getElementById("apiKeyDisplay").innerText;
            navigator.clipboard.writeText(t).then(() => {
                const btn = event.currentTarget;
                const oldHTML = btn.innerHTML;
                btn.innerHTML = '<iconify-icon icon="solar:check-circle-bold" class="text-lg"></iconify-icon> Copied!';
                btn.classList.replace('btn-primary', 'btn-success');
                setTimeout(() => {
                    btn.innerHTML = oldHTML;
                    btn.classList.replace('btn-success', 'btn-primary');
                }, 2000);
            });
        }
        function previewAvatar(input) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = e => document.getElementById('upPreview').src = e.target.result;
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>


