<?php 

session_start();

// PREVENT CACHING - Force fresh data on every load
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

if (isset($_SESSION['user_email'])){

	require '../../config.php';
	require '../functions.php';

	$connect = connect($database);


	if (empty($_GET["id"]) ) {
		header('Location: ./stores.php');
	}

	$check_access = check_access($connect);

	if ($check_access['user_role'] == 1 || $check_access['user_role'] == 2){

		if ($_SERVER['REQUEST_METHOD'] == 'POST'){

			// Initialize status message
			$upload_status = '';
			$upload_error = '';

			$store_id = cleardata($_POST['store_id']);
			$store_title = cleardata($_POST['store_title']);
			$store_seotitle = cleardata($_POST['store_seotitle']);
			$store_description = cleardata($_POST['store_description']);
			$store_seodescription = cleardata($_POST['store_seodescription']);
			$store_featured = cleardata($_POST['store_featured']);
			$store_status = cleardata($_POST['store_status']);
			
			// Handle parent and subcategory selection
			$parent_category = !empty($_POST['parent_category']) ? cleardata($_POST['parent_category']) : NULL;
			$subcategory = !empty($_POST['subcategory']) ? cleardata($_POST['subcategory']) : NULL;
			
			// Build category array
			// IMPORTANT: If subcategory is selected, save ONLY the subcategory ID
			// If no subcategory, save only the parent category ID
			$store_categories = array();
			if ($subcategory) {
				// Subcategory selected - save only subcategory ID
				$store_categories[] = $subcategory;
				$store_category = $subcategory; // For backward compatibility
			} elseif ($parent_category) {
				// No subcategory - save only parent category ID
				$store_categories[] = $parent_category;
				$store_category = $parent_category; // For backward compatibility
			} else {
				$store_category = NULL;
			}

			// Auto-generate SEO title if empty
			if (empty($store_seotitle)) {
				$store_seotitle = $store_title . " Coupons, Deals & Cashback Offers | Alonedeals";
			}
			
			// Auto-generate SEO description if empty
			if (empty($store_seodescription)) {
				$store_seodescription = "Get the latest " . $store_title . " coupons, promo codes & exclusive cashback offers on Alonedeals. Save more on every purchase today!";
			}
			
			// Auto-generate store description if empty
			if (empty($store_description)) {
				// Get category name for better description
				$category_name = '';
				$product_type = 'products';
				
				if ($subcategory) {
					$cat_query = $connect->prepare("SELECT subcategory_title FROM subcategories WHERE subcategory_id = :id");
					$cat_query->execute([':id' => $subcategory]);
					$cat_result = $cat_query->fetch(PDO::FETCH_ASSOC);
					if ($cat_result) {
						$category_name = $cat_result['subcategory_title'];
						$product_type = strtolower($category_name);
					}
				} elseif ($parent_category) {
					$cat_query = $connect->prepare("SELECT category_title FROM categories WHERE category_id = :id");
					$cat_query->execute([':id' => $parent_category]);
					$cat_result = $cat_query->fetch(PDO::FETCH_ASSOC);
					if ($cat_result) {
						$category_name = $cat_result['category_title'];
						$product_type = strtolower($category_name);
					}
				}
				
				// Generate description with dynamic content
				$store_description = "At Alonedeals, you can find the latest " . $store_title . " coupon codes, deals, and cashback offers to help you save more on every purchase. Whether you're shopping for " . $product_type . " or daily essentials, our verified deals ensure maximum savings.";
			}

			$store_slug = cleardata($_POST['store_slug']);

			if (empty($store_slug)) {
				$slug = $_POST['store_slug_save'];
			}else{

				$converted_slug = convertSlug($_POST['store_slug']);
				$exists = get_store_slug($connect, $converted_slug);

				if ($exists > 0)
				{
					$new_number = $exists + 1;
					$slug = $converted_slug."-".$new_number;

				}else{

					$slug = $converted_slug;
				}
			}

			// Handle CDN fields - Auto-enable if URL is provided
			$store_image_cdn_url = isset($_POST['store_image_cdn_url']) ? cleardata($_POST['store_image_cdn_url']) : '';
			$store_use_cdn = !empty($store_image_cdn_url) ? 1 : 0; // Auto-enable if URL exists
			
			// Debug logging
			error_log("=== STORE CDN SAVE DEBUG ===");
			error_log("CDN URL from POST: " . $store_image_cdn_url);
			error_log("Use CDN (auto-set): " . $store_use_cdn);
			error_log("Store ID: " . $store_id);

			$image_type = isset($_POST['image_type']) ? $_POST['image_type'] : 'keep';
			$store_image = $_POST['store_image_save']; // Default to current image

			// Debug: Log what we received
			error_log("=== STORE IMAGE DEBUG ===");
			error_log("Image Type: " . $image_type);
			error_log("POST data: " . print_r($_POST, true));
			if (isset($_POST['image_url'])) {
				error_log("Image URL from POST: " . $_POST['image_url']);
			}

			// Handle Image URL - Just save the URL, don't download
			if ($image_type == 'url' && !empty($_POST['image_url'])) {
				$image_url = trim($_POST['image_url']);
				
				// Validate URL
				if (filter_var($image_url, FILTER_VALIDATE_URL)) {
					$store_image_cdn_url = $image_url;
					$store_use_cdn = 1;
					$upload_status = "External image URL saved: " . $image_url;
					error_log("External image URL saved: " . $image_url);
				} else {
					$upload_error = "Invalid URL format";
					error_log("Invalid URL format: " . $image_url);
				}
			}
			// Handle File Upload
			else if ($image_type == 'upload' && isset($_FILES['store_image']) && $_FILES['store_image']['error'] == 0) {
				$extsAllowed = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'avif');
				$extUpload = strtolower( substr( strrchr($_FILES['store_image']['name'], '.') ,1) ) ;
	 
				if (in_array($extUpload, $extsAllowed) ) { 
		
					$image = $_FILES['store_image']['tmp_name'];
					$imagefile = explode(".", $_FILES["store_image"]["name"]);
					$renamefile = round(microtime(true)) . '.' . end($imagefile);
					$image_upload = '../../images/';
					move_uploaded_file($image, $image_upload . 'store_' . $renamefile);
					$store_image = 'store_' . $renamefile;
				}
			}

			$statment = $connect->prepare("UPDATE stores SET store_id = :store_id, store_title = :store_title, store_slug = :store_slug, store_description = :store_description, store_seotitle = :store_seotitle, store_seodescription = :store_seodescription, store_featured = :store_featured, store_category = :store_category, store_status = :store_status, store_image = :store_image, store_image_cdn_url = :store_image_cdn_url, store_use_cdn = :store_use_cdn WHERE store_id = :store_id");

			$statment->execute(array(
				':store_id' => $store_id,
				':store_title' => $store_title,
				':store_slug' => $slug,
				':store_description' => $store_description,
				':store_seotitle' => $store_seotitle,
				':store_seodescription' => $store_seodescription,
				':store_featured' => $store_featured,
				':store_category' => $store_category,
				':store_status' => $store_status,
				':store_image' => $store_image,
				':store_image_cdn_url' => $store_image_cdn_url,
				':store_use_cdn' => $store_use_cdn
			));
			
			// Debug: Verify what was saved
			error_log("Store updated successfully");
			error_log("Saved CDN URL: " . $store_image_cdn_url);
			error_log("Saved Use CDN: " . $store_use_cdn);

			// Update store_categories junction table
			// First, delete existing category associations
			$delete_stmt = $connect->prepare("DELETE FROM store_categories WHERE store_id = :store_id");
			$delete_stmt->execute(array(':store_id' => $store_id));
			
			// Then insert new category associations (parent and/or subcategory)
			if (!empty($store_categories)) {
				$insert_stmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (:store_id, :category_id)");
				foreach ($store_categories as $category_id) {
					$insert_stmt->execute(array(
						':store_id' => $store_id,
						':category_id' => $category_id
					));
				}
			}

			// Build redirect URL properly with cache-busting timestamp
			$redirect_url = $_SERVER['HTTP_REFERER'];
			
			// Add timestamp to force browser refresh
			$separator = (strpos($redirect_url, '?') !== false) ? '&' : '?';
			$redirect_url .= $separator . 't=' . time();
			
			$params = array();
			
			if ($upload_status) {
				$params[] = 'status=' . urlencode($upload_status);
			}
			if ($upload_error) {
				$params[] = 'error=' . urlencode($upload_error);
			}
			
			if (!empty($params)) {
				$redirect_url .= '&' . implode('&', $params);
			}
			
			header('Location: ' . $redirect_url);
			exit;

		}else{

			$id_store = id_store($_GET['id']);
			
			// Debug: Log what ID we're trying to load
			error_log("Edit Store - Requested ID from GET: " . $_GET['id']);
			error_log("Edit Store - Processed ID: " . $id_store);

			$store = get_store_per_id($connect, $id_store);
			
			// Debug: Log the result
			error_log("Edit Store - Query result: " . ($store ? "Found" : "Not found"));
			if ($store) {
				error_log("Edit Store - Store Title: " . $store[0]['store_title']);
			}

			if (!$store){
				error_log("Store not found for ID: " . $id_store);
				header('Location: ./stores.php');
				exit;
			}

			$store = $store['0'];
			
			// Debug: Check if store data is loaded
			if (empty($store)) {
				error_log("Store data is empty after fetching");
				header('Location: ./stores.php');
				exit;
			}
			
	$categories = get_all_categories($connect);
	
	// Get all subcategories
	$subcategories_query = $connect->query("SELECT * FROM subcategories WHERE subcategory_status = 1 ORDER BY subcategory_title");
	$all_subcategories = $subcategories_query->fetchAll(PDO::FETCH_ASSOC);
	
	// Get current store categories
	$store_category_stmt = $connect->prepare("SELECT category_id FROM store_categories WHERE store_id = :store_id");
	$store_category_stmt->execute(array(':store_id' => $store['store_id']));
	$store_categories = $store_category_stmt->fetchAll(PDO::FETCH_COLUMN);
	
	require '../views/header.view.php';
			require '../views/edit.store.view.php';
		}
		
} else {

		header('Location:'.SITE_URL);
	}

	require '../views/footer.view.php';

} else {
	header('Location: ./login.php');		
}


?>