<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();
$conn = require __DIR__ . '/../../app/config/database.php';
$u = current_user();

if (is_post() && isset($_FILES['photo'])) {
  csrf_verify();

  $f = $_FILES['photo'];
  if ($f['error'] === 0 && in_array(mime_content_type($f['tmp_name']), ['image/jpeg','image/png'])) {
    $name = 'profile_'.$u['id'].'_'.time().'.jpg';
    $path = '/uploads/profiles/'.$name;
    move_uploaded_file($f['tmp_name'], __DIR__.'/../../public'.$path);

    $st = $conn->prepare("UPDATE users SET photo=? WHERE id=?");
    $st->bind_param("si", $path, $u['id']);
    $st->execute();

    $_SESSION['user']['photo'] = $path;
    flash('msg','Profile photo updated.');
  } else {
    flash('err','Invalid image.');
  }
  redirect('profile_photo.php');
}

$title = 'Profile Photo';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<div class="container py-4" style="margin-left:240px">
  <?php if($m=flash('msg')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?>

  <div class="card ab-card p-4" style="max-width:400px">
    <h5 class="fw-bold mb-3">Profile Photo</h5>

    <img src="<?= e($u['photo'] ?? '/assets/avatar.png') ?>" class="rounded-circle mb-3" width="120">

    <form method="post" enctype="multipart/form-data">
      <?= csrf_field() ?>
      <input type="file" name="photo" class="form-control mb-3" required>
      <button class="btn ab-btn text-white w-100">Upload</button>
    </form>
  </div>
</div>
