/home/awneajlw/www/codestechvista.com/save-shop-basic.php
<?php
/**
 * Save Shop Basic Details and Create User Account
 * This file handles shop registration and creates the user account
 * Uses email from session to complete the registration process
 */

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include required files
require_once 'config/database.php';  // Database connection configuration
require_once 'includes/auth.php';    // Authentication functions

$database = new Database();
$db = $database->getConnection();

// Get email from session (from registration flow)
$email = $_SESSION['registration_email'] ?? '';

if (empty($email)) {
    // If no email in session, redirect to registration
    header('Location: register.php');
    exit();
}

// Get form data
$shop_name = sanitizeInput($_POST['shop_name'] ?? '');
$phone_username = sanitizeInput($_POST['phone'] ?? ''); // This now contains phone/username
$password = sanitizeInput($_POST['password'] ?? '');

// Validate required fields
if (empty($shop_name) || empty($phone_username) || empty($password)) {
    header('Location: shop-registration-form.php?error=missing_fields');
    exit();
}

// Determine if phone_username is a phone number or username
// If it contains only digits and is 10+ chars, treat as phone, otherwise as username
$is_phone = preg_match('/^\d{10,}$/', $phone_username);
$phone = $is_phone ? $phone_username : '';
$username = $is_phone ? 'user_' . substr($phone_username, -4) : $phone_username;

try {
    // Check if user already exists
    $check_query = "SELECT id FROM users WHERE email = ?";
    $check_stmt = $db->prepare($check_query);
    $check_stmt->execute([$email]);
    
    $user_id = null;
    
    if ($check_stmt->rowCount() > 0) {
        // User exists, get user ID
        $existing_user = $check_stmt->fetch(PDO::FETCH_ASSOC);
        $user_id = $existing_user['id'];
        
        // Update user with additional details
        $update_query = "UPDATE users SET name = ?, phone = ?, password = ?, email_verified = 1, registration_step = 2 WHERE id = ?";
        $update_stmt = $db->prepare($update_query);
        $hashed_password = hashPassword($password);
        $update_stmt->execute([$username, $phone, $hashed_password, $user_id]);
    } else {
        // Create new user
        $insert_query = "INSERT INTO users (name, email, phone, password, role, email_verified, registration_step) VALUES (?, ?, ?, ?, 'user', 1, 2)";
        $insert_stmt = $db->prepare($insert_query);
        $hashed_password = hashPassword($password);
        $insert_stmt->execute([$username, $email, $phone, $hashed_password]);
        $user_id = $db->lastInsertId();
    }

// Handle file upload
$logo_path = '';
if (isset($_FILES['shop_logo']) && $_FILES['shop_logo']['error'] === UPLOAD_ERR_OK) {
    $upload_dir = 'assets/images/logos/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $file_extension = pathinfo($_FILES['shop_logo']['name'], PATHINFO_EXTENSION);
    $logo_filename = 'logo_' . $user_id . '_' . time() . '.' . $file_extension;
    $logo_path = $upload_dir . $logo_filename;
    
    if (move_uploaded_file($_FILES['shop_logo']['tmp_name'], $logo_path)) {
        $logo_path = $logo_path;
    }
}

// Update or insert shop data
$query = "INSERT INTO shops (user_id, shop_name, shop_address, shop_phone, shop_logo, shop_email) 
          VALUES (?, ?, '', ?, ?, '') 
          ON DUPLICATE KEY UPDATE 
          shop_name = VALUES(shop_name),
          shop_phone = VALUES(shop_phone),
          shop_logo = VALUES(shop_logo)";

$stmt = $db->prepare($query);
$success = $stmt->execute([
    $user_id,
    $shop_name,
    $phone,
    $logo_path
]);

    if ($success) {
        // Store user_id in session for next steps
        $_SESSION['user_id'] = $user_id;
        $_SESSION['registration_step'] = 2;
        
        // Redirect to social media registration
        header('Location: social-media-reg.php');
        exit();
    } else {
        // Error occurred
        header('Location: shop-registration-form.php?error=database_error');
        exit();
    }
    
} catch (Exception $e) {
    // Database error
    error_log("Registration error: " . $e->getMessage());
    header('Location: shop-registration-form.php?error=database_error');
    exit();
}
?>