<?php
session_start();
include 'layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

try {
    if (!isset($_FILES['document']) || $_FILES['document']['error'] === UPLOAD_ERR_NO_FILE) {
        throw new Exception('No file uploaded');
    }

    $file = $_FILES['document'];
    $member_no = $_POST['member_no'];
    $corp_id = $_POST['corp_id'];
    $doc_type = $_POST['doc_type'];
    $description = $_POST['description'];

    // Validate file type and size
    $allowed_types = ['application/pdf', 'image/jpeg', 'image/png', 'application/msword'];
    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception('Invalid file type');
    }

    if ($file['size'] > 5 * 1024 * 1024) { // 5MB limit
        throw new Exception('File size too large');
    }

    // Create upload directory structure
    $base_dir = 'documents/';
    $corp_dir = $base_dir . $corp_id . '/';
    $member_dir = $corp_dir . $member_no . '/';
    
    foreach ([$base_dir, $corp_dir, $member_dir] as $dir) {
        if (!file_exists($dir)) {
            mkdir($dir, 0755, true);
        }
    }

    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $new_filename = uniqid() . '_' . date('Ymd') . '.' . $extension;
    $upload_path = $member_dir . $new_filename;

    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
        throw new Exception('Failed to upload file');
    }

    // Save document record
    $sql = "INSERT INTO client_documents (
        member_no,
        corp_id,
        doc_type,
        filename,
        original_name,
        file_path,
        description,
        uploaded_by,
        uploaded_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sssssssi',
        $member_no,
        $corp_id,
        $doc_type,
        $new_filename,
        $file['name'],
        $upload_path,
        $description,
        $_SESSION['user_id']
    );

    if (!$stmt->execute()) {
        throw new Exception('Failed to save document record');
    }

    echo json_encode(['success' => true, 'message' => 'Document uploaded successfully']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

$conn->close();
?>