<?php
/**
 * Update Store Information
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$userId = $_SESSION['user_id'];
$storeId = intval($_POST['store_id'] ?? 0);

// Verify user owns this store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreById($storeId);

if (!$store || $store['owner_id'] != $userId) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Prepare update data
$updateData = [];

// Store name cannot be changed after creation for security (permanent URL)
// Explicitly reject any attempts to change store name
if (isset($_POST['store_name'])) {
    echo json_encode(['success' => false, 'message' => 'Store name cannot be changed after creation for security reasons']);
    exit();
}

if (isset($_POST['description'])) {
    $updateData['description'] = trim($_POST['description']);
}

if (isset($_POST['phone'])) {
    $updateData['phone'] = trim($_POST['phone']);
}

if (isset($_POST['momo_name'])) {
    $updateData['momo_name'] = trim($_POST['momo_name']);
}

if (isset($_POST['whatsapp'])) {
    $updateData['whatsapp'] = trim($_POST['whatsapp']);
}

if (isset($_POST['whatsapp_group_link'])) {
    $whatsappGroupLink = trim($_POST['whatsapp_group_link']);
    // Validate URL format if provided
    if (!empty($whatsappGroupLink) && !filter_var($whatsappGroupLink, FILTER_VALIDATE_URL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid WhatsApp group link format. Please enter a valid URL (e.g., https://chat.whatsapp.com/xxxxxxxxxx).']);
        exit();
    }
    $updateData['whatsapp_group_link'] = $whatsappGroupLink;
}

// Handle logo upload
if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    $maxFileSize = 2 * 1024 * 1024; // 2MB
    
    $fileType = $_FILES['logo']['type'];
    $fileSize = $_FILES['logo']['size'];
    $fileName = $_FILES['logo']['name'];
    $fileTmpName = $_FILES['logo']['tmp_name'];
    
    // Validate file type
    if (!in_array($fileType, $allowedTypes)) {
        echo json_encode(['success' => false, 'message' => 'Invalid file type. Please upload JPG, PNG, GIF, or WEBP image.']);
        exit();
    }
    
    // Validate file size
    if ($fileSize > $maxFileSize) {
        echo json_encode(['success' => false, 'message' => 'File size too large. Maximum size is 2MB.']);
        exit();
    }
    
    // Generate unique filename
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $newFileName = 'store_' . $storeId . '_' . time() . '_' . uniqid() . '.' . $fileExtension;
    $uploadDir = '../uploads/stores/';
    
    // Create uploads/stores directory if it doesn't exist
    if (!file_exists($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            echo json_encode(['success' => false, 'message' => 'Failed to create upload directory. Please check permissions.']);
            exit();
        }
    }
    
    // Ensure directory is writable
    if (!is_writable($uploadDir)) {
        echo json_encode(['success' => false, 'message' => 'Upload directory is not writable. Please check permissions.']);
        exit();
    }
    
    $uploadPath = $uploadDir . $newFileName;
    
    // Move uploaded file
    if (move_uploaded_file($fileTmpName, $uploadPath)) {
        // Verify file was actually moved
        if (!file_exists($uploadPath)) {
            echo json_encode(['success' => false, 'message' => 'File upload failed. Please try again.']);
            exit();
        }
        
        // Delete old logo if exists
        if (!empty($store['logo_url'])) {
            $oldLogoPath = '../' . ltrim($store['logo_url'], './');
            if (file_exists($oldLogoPath)) {
                @unlink($oldLogoPath);
            }
        }
        
        // Store relative path from root (without leading slash)
        $updateData['logo_url'] = 'uploads/stores/' . $newFileName;
    } else {
        $errorMsg = 'Failed to upload logo.';
        if ($_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
            switch ($_FILES['logo']['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $errorMsg = 'File size too large. Maximum size is 2MB.';
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $errorMsg = 'File upload was incomplete. Please try again.';
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $errorMsg = 'No file was uploaded.';
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                    $errorMsg = 'Missing temporary folder.';
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $errorMsg = 'Failed to write file to disk. Please check permissions.';
                    break;
                case UPLOAD_ERR_EXTENSION:
                    $errorMsg = 'File upload stopped by extension.';
                    break;
            }
        }
        echo json_encode(['success' => false, 'message' => $errorMsg]);
        exit();
    }
}

// Handle hero colors
if (isset($_POST['hero_color_1'])) {
    $heroColor1 = trim($_POST['hero_color_1']);
    // Validate hex color format
    if (preg_match('/^#[0-9A-Fa-f]{6}$/', $heroColor1)) {
        $updateData['hero_color_1'] = $heroColor1;
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid hero color 1 format. Please use hex format (e.g., #3b82f6).']);
        exit();
    }
}

if (isset($_POST['hero_color_2'])) {
    $heroColor2 = trim($_POST['hero_color_2']);
    // Validate hex color format
    if (preg_match('/^#[0-9A-Fa-f]{6}$/', $heroColor2)) {
        $updateData['hero_color_2'] = $heroColor2;
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid hero color 2 format. Please use hex format (e.g., #8b5cf6).']);
        exit();
    }
}

// Update store
$result = $storeManager->updateStore($storeId, $updateData);

echo json_encode($result);
?>




