<?php
session_start();
include "../php/db_connect.php";

if (!isset($_SESSION['user_id'])) {
  header("Location: ../login.php");
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  header("Location: admin.php?page=profile");
  exit;
}

$shop_id = $_SESSION['user_id'];

$shop_name = trim($_POST['shop_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$mobile_number = trim($_POST['mobile_number'] ?? '');
$address = trim($_POST['address'] ?? '');

if ($shop_name === '' || $email === '' || $mobile_number === '' || $address === '') {
  header("Location: admin.php?page=profile&error=empty_fields");
  exit;
}

// Get current image
$stmt = $conn->prepare("SELECT shop_image FROM users WHERE id = ?");
$stmt->bind_param("i", $shop_id);
$stmt->execute();
$result = $stmt->get_result();
$currentShop = $result->fetch_assoc();

$shop_image = $currentShop['shop_image'] ?? "";

// If image is uploaded
if (isset($_FILES['shop_image']) && $_FILES['shop_image']['error'] === 0) {

  $uploadDir = "../uploads/shops/";

  if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
  }

  $fileName = $_FILES['shop_image']['name'];
  $fileTmp = $_FILES['shop_image']['tmp_name'];
  $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

  $allowedTypes = ['jpg', 'jpeg', 'png', 'webp'];

  if (!in_array($fileExt, $allowedTypes)) {
    header("Location: admin.php?page=profile&error=invalid_image");
    exit;
  }

  $newFileName = "shop_" . $shop_id . "_" . time() . "." . $fileExt;
  $targetPath = $uploadDir . $newFileName;

  if (move_uploaded_file($fileTmp, $targetPath)) {
    $shop_image = $newFileName;
  } else {
    header("Location: admin.php?page=profile&error=upload_failed");
    exit;
  }
}

// Update profile
$stmt = $conn->prepare("
  UPDATE users
  SET shop_name = ?, email = ?, mobile_number = ?, address = ?, shop_image = ?
  WHERE id = ?
");

$stmt->bind_param("sssssi", $shop_name, $email, $mobile_number, $address, $shop_image, $shop_id);

if ($stmt->execute()) {
  $_SESSION['shop_name'] = $shop_name;
  header("Location: admin.php?page=profile&success=1");
  exit;
} else {
  header("Location: admin.php?page=profile&error=update_failed");
  exit;
}
?>