<?php
require_once __DIR__ . '/config/config.php';
require_login();
$u = current_user();

if (!is_dir(SIGNATURE_UPLOAD_DIR)) { @mkdir(SIGNATURE_UPLOAD_DIR, 0755, true); }

$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_email'])) {
        $email = trim($_POST['email'] ?? '');
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } else {
            $pdo->prepare("UPDATE users SET email = ? WHERE id = ?")->execute([$email ?: null, $u['id']]);
            $_SESSION['user']['email'] = $email;
            $success = 'Email address updated. You will now receive approval notifications here.';
        }
    } elseif (isset($_POST['upload_signature']) && !empty($_FILES['signature']['name'])) {
        $file = $_FILES['signature'];
        $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg'];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $error = 'Upload failed. Please try again.';
        } elseif ($file['size'] > 1024 * 1024) {
            $error = 'Signature image must be under 1MB.';
        } elseif (!isset($allowed[$file['type']])) {
            $error = 'Only PNG or JPG images are allowed.';
        } else {
            $ext = $allowed[$file['type']];
            $filename = 'user_' . $u['id'] . '_' . time() . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], SIGNATURE_UPLOAD_DIR . $filename)) {
                // remove old signature file if any
                $stmt = $pdo->prepare("SELECT signature_path FROM users WHERE id=?");
                $stmt->execute([$u['id']]);
                $old = $stmt->fetchColumn();
                if ($old && file_exists(SIGNATURE_UPLOAD_DIR . basename($old))) {
                    @unlink(SIGNATURE_UPLOAD_DIR . basename($old));
                }
                $pdo->prepare("UPDATE users SET signature_path = ? WHERE id = ?")->execute([$filename, $u['id']]);
                $_SESSION['user']['signature_path'] = $filename;
                $success = 'Signature uploaded. It will now appear on your approval actions.';
            } else {
                $error = 'Could not save the uploaded file.';
            }
        }
    }
}

$stmt = $pdo->prepare("SELECT email, signature_path FROM users WHERE id = ?");
$stmt->execute([$u['id']]);
$profile = $stmt->fetch();

$pageTitle = 'My Profile';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">My Profile</h1>

<?php if ($error): ?><div class="mb-4 bg-red-50 border border-red-200 text-red-700 text-sm px-4 py-2.5 rounded-lg max-w-lg"><?= e($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="mb-4 bg-emerald-50 border border-emerald-200 text-emerald-700 text-sm px-4 py-2.5 rounded-lg max-w-lg"><?= e($success) ?></div><?php endif; ?>

<div class="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-3xl">
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
    <h2 class="font-semibold mb-1">Email Address</h2>
    <p class="text-xs text-slate-500 mb-4">Used to send you approval workflow notifications.</p>
    <form method="POST" class="space-y-3">
      <input type="email" name="email" placeholder="you@bestwesternplusyenagoa.com" value="<?= e($profile['email'] ?? '') ?>"
        class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <button type="submit" name="save_email" value="1" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Save Email</button>
    </form>
  </div>

  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
    <h2 class="font-semibold mb-1">Approval Signature</h2>
    <p class="text-xs text-slate-500 mb-4">A PNG/JPG (under 1MB) of your signature, shown next to your approvals.</p>
    <?php if (!empty($profile['signature_path'])): ?>
      <div class="mb-4 border border-slate-200 rounded-lg p-3 bg-slate-50 inline-block">
        <img src="<?= SIGNATURE_UPLOAD_URL . e($profile['signature_path']) ?>" alt="Current signature" class="h-16">
      </div>
    <?php endif; ?>
    <form method="POST" enctype="multipart/form-data" class="space-y-3">
      <input type="file" name="signature" accept="image/png,image/jpeg" required
        class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <button type="submit" name="upload_signature" value="1" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Upload Signature</button>
    </form>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
