<?php
// account.php — any logged-in user (their own account only).
require_once 'includes/auth.php';
require_login();

require_once 'db.php';

$me = current_user();
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_signature'])) {
    require_csrf();

    $removeSignature = isset($_POST['remove_signature']);
    $current = $pdo->prepare("SELECT Signature_Path FROM tbl_users WHERE UserID = ?");
    $current->execute([$me['id']]);
    $signaturePath = $current->fetchColumn();

    if ($removeSignature) {
        $signaturePath = null;
    }

    if (isset($_FILES['signature']) && $_FILES['signature']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $_FILES['signature']['tmp_name']);
        finfo_close($finfo);

        if (isset($allowedTypes[$mime]) && $_FILES['signature']['size'] <= 3 * 1024 * 1024) {
            $uploadDir = __DIR__ . '/uploads/signatures/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            $filename = 'sig_' . $me['id'] . '_' . bin2hex(random_bytes(8)) . '.' . $allowedTypes[$mime];
            move_uploaded_file($_FILES['signature']['tmp_name'], $uploadDir . $filename);
            $signaturePath = 'uploads/signatures/' . $filename;
        } else {
            $error = 'Signature file must be JPG/PNG/WEBP under 3MB.';
        }
    }

    if (!$error) {
        $upd = $pdo->prepare("UPDATE tbl_users SET Signature_Path = ? WHERE UserID = ?");
        $upd->execute([$signaturePath, $me['id']]);
        $message = 'Signature saved. It will now appear on certificates where you are listed as Inspector/Engineer or Trainer/Assessor.';
    }
}

$stmt = $pdo->prepare("SELECT * FROM tbl_users WHERE UserID = ?");
$stmt->execute([$me['id']]);
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Account — Liftek</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container my-4" style="max-width: 600px;">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold m-0"><i class="fa-solid fa-user-circle text-primary me-2"></i> My Account</h3>
        <a href="index.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left me-1"></i> Back</a>
    </div>

    <div class="card mb-4">
        <div class="card-body">
            <p class="mb-1"><strong>Name:</strong> <?= htmlspecialchars($userRow['Name']); ?></p>
            <p class="mb-1"><strong>Email:</strong> <?= htmlspecialchars($userRow['Email']); ?></p>
            <p class="mb-0"><strong>Role:</strong> <span class="badge bg-secondary text-capitalize"><?= htmlspecialchars($userRow['Role']); ?></span></p>
        </div>
    </div>

    <?php if ($message): ?><div class="alert alert-success py-2"><?= htmlspecialchars($message); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger py-2"><?= htmlspecialchars($error); ?></div><?php endif; ?>

    <div class="card">
        <div class="card-header bg-primary text-white fw-bold"><i class="fa-solid fa-signature me-1"></i> My Signature</div>
        <div class="card-body">
            <p class="small text-muted">This appears automatically on every certificate where you're listed as the Inspector/Engineer or Trainer/Assessor — no need to sign printed copies by hand.</p>

            <?php if (!empty($userRow['Signature_Path'])): ?>
                <div class="mb-3 p-2 border rounded d-inline-block bg-white">
                    <img src="<?= htmlspecialchars($userRow['Signature_Path']); ?>" style="max-height: 60px; display:block;">
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="save_signature" value="1">
                <?php csrf_field(); ?>

                <?php if (!empty($userRow['Signature_Path'])): ?>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="remove_signature" id="removeSig" value="1">
                        <label class="form-check-label small" for="removeSig">Remove my current signature</label>
                    </div>
                <?php endif; ?>

                <label class="form-label small fw-bold">Upload New Signature (JPG/PNG/WEBP, transparent background recommended)</label>
                <input type="file" name="signature" accept="image/jpeg,image/png,image/webp" class="form-control mb-3">

                <button type="submit" class="btn btn-primary fw-bold"><i class="fa-solid fa-save me-1"></i> Save</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>
