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

// Function to sanitize input
function sanitize_input($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_kyc'])) {
    
    if (!isset($_SESSION['username'])) {
        header("Location: ../index");
        exit();
    }
    
    // Retrieve User ID based on session
    $mobile = $_SESSION['username'];
    $userQuery = "SELECT id FROM users WHERE mobile = '$mobile' LIMIT 1";
    $userResult = mysqli_query($conn, $userQuery);
    
    if (!$userResult || mysqli_num_rows($userResult) == 0) {
        die("User not found.");
    }
    
    $userRow = mysqli_fetch_assoc($userResult);
    $user_id = $userRow['id'];
    
    // Collect Form Data
    $full_name = sanitize_input($_POST['full_name']);
    $aadhaar_number = sanitize_input($_POST['aadhaar_number']);
    $dob = sanitize_input($_POST['dob']);
    
    // Create 'kyc_docs' directory if it doesn't exist
    $target_dir = "../assets/kyc_docs/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    // Handle File Upload
    $file_name = basename($_FILES["aadhaar_image"]["name"]);
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $new_file_name = "aadhaar_" . $user_id . "_" . time() . "." . $file_ext;
    $target_file = $target_dir . $new_file_name;
    $uploadOk = 1;
    
    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["aadhaar_image"]["tmp_name"]);
    if($check === false) {
        echo "<script>alert('File is not an image.'); window.location.href='../dashboard.php';</script>";
        $uploadOk = 0;
    }
    
    // Check file size (2MB max)
    if ($_FILES["aadhaar_image"]["size"] > 2000000) {
        echo "<script>alert('Sorry, your file is too large. Max 2MB allowed.'); window.location.href='../dashboard.php';</script>";
        $uploadOk = 0;
    }
    
    // Allow certain file formats
    if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg") {
        echo "<script>alert('Sorry, only JPG, JPEG, PNG files are allowed.'); window.location.href='../dashboard.php';</script>";
        $uploadOk = 0;
    }
    
    // If everything is ok, try to upload file
    if ($uploadOk == 1) {
        if (move_uploaded_file($_FILES["aadhaar_image"]["tmp_name"], $target_file)) {
            
            // Insert into kyc_documents table
            // First check if table exists, if not create it (Rudimentary check/create)
            $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'kyc_documents'");
            if (mysqli_num_rows($tableCheck) == 0) {
                $createTable = "CREATE TABLE kyc_documents (
                    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    user_id INT(11) NOT NULL,
                    full_name VARCHAR(255) NOT NULL,
                    aadhaar_number VARCHAR(20) NOT NULL,
                    dob DATE NOT NULL,
                    aadhaar_image VARCHAR(255) NOT NULL,
                    status ENUM('Pending', 'Approved', 'Rejected') DEFAULT 'Pending',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )";
                if (!mysqli_query($conn, $createTable)) {
                    die("Error creating table: " . mysqli_error($conn));
                }
            }
            
            // Check if a pending request already exists for this user
            $checkExisting = mysqli_query($conn, "SELECT id FROM kyc_documents WHERE user_id = '$user_id' AND status = 'Pending'");
            if (mysqli_num_rows($checkExisting) > 0) {
                 echo "<script>alert('A KYC request is already pending approval.'); window.location.href='../dashboard';</script>";
                 exit;
            }
            
            // Insert
            $insertQuery = "INSERT INTO kyc_documents (user_id, full_name, aadhaar_number, dob, aadhaar_image, status) VALUES ('$user_id', '$full_name', '$aadhaar_number', '$dob', '$new_file_name', 'Pending')";
            
            if (mysqli_query($conn, $insertQuery)) {
                // Update users table to reflect pending status if needed, but we rely on kyc_documents for status
                 echo "<script>alert('KYC validation submitted successfully! Please wait for Admin approval.'); window.location.href='../dashboard';</script>";
            } else {
                 echo "Error: " . $insertQuery . "<br>" . mysqli_error($conn);
            }
            
        } else {
            echo "<script>alert('Sorry, there was an error uploading your file.'); window.location.href='../dashboard';</script>";
        }
    }
}
?>
