<?php
session_start();
include 'config.php';

$user_id = $_SESSION['user_id'];
if (!$user_id) {
    echo '<script>showToast("Error!", "Please login first.", "danger");</script>';
    exit;
}

// Validate inputs
$document_type = mysqli_real_escape_string($conn, $_POST['address_document_type']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$postal_code = mysqli_real_escape_string($conn, $_POST['postal_code']);

if (!$document_type || !$city || !$postal_code) {
    echo '<script>showToast("Error!", "Please fill all required fields.", "danger");</script>';
    exit;
}

// Handle file upload
if (!isset($_FILES['address_file']) || $_FILES['address_file']['error'] != 0) {
    echo '<script>showToast("Error!", "Please upload a document file.", "danger");</script>';
    exit;
}

$file = $_FILES['address_file'];
$allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
$max_size = 10 * 1024 * 1024;

if (!in_array($file['type'], $allowed_types)) {
    echo '<script>showToast("Error!", "Invalid file type. Only JPG, PNG, PDF allowed.", "danger");</script>';
    exit;
}

if ($file['size'] > $max_size) {
    echo '<script>showToast("Error!", "File too large. Maximum 10MB allowed.", "danger");</script>';
    exit;
}

// Create upload directory
$upload_dir = 'uploads/kyc/' . $user_id . '/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Generate unique filename
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$filename = 'address_' . time() . '_' . uniqid() . '.' . $file_ext;
$filepath = $upload_dir . $filename;

// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
    echo '<script>showToast("Error!", "Failed to upload file. Please try again.", "danger");</script>';
    exit;
}

// Insert into database
$insert_sql = "INSERT INTO kyc_documents 
              (user_id, document_type, document_path, upload_date, verification_status) 
              VALUES 
              ('$user_id', '$document_type', '$filepath', NOW(), 'pending')";

if (mysqli_query($conn, $insert_sql)) {
    // Update user address info
    $address = mysqli_real_escape_string($conn, $_POST['street_address']);
    $update_sql = "UPDATE users SET 
                   address = '$address',
                   city = '$city',
                   postal_code = '$postal_code',
                   verification_completed = 1 
                   WHERE id = '$user_id'";
    mysqli_query($conn, $update_sql);
    
    echo '<script>showToast("Success!", "Address document uploaded successfully!", "success");</script>';
    echo '<script>setTimeout(() => location.reload(), 1500);</script>';
} else {
    unlink($filepath);
    echo '<script>showToast("Error!", "Database error: ' . mysqli_error($conn) . '", "danger");</script>';
}
?>