<?php
require_once '../config/database.php';
header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    $database = new Database();
    $pdo = $database->getConnection();

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

    // Validate required fields
    $required_fields = ['first_name', 'last_name', 'email', 'phone', 'college', 'course', 'membership_type'];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            echo json_encode(['success' => false, 'message' => "Field '{$field}' is required"]);
            exit;
        }
    }
    
    // Validate family membership has dependents
    if ($_POST['membership_type'] === 'Family') {
        $dependents = json_decode($_POST['dependents'] ?? '[]', true);
        if (empty($dependents) || !is_array($dependents)) {
            echo json_encode(['success' => false, 'message' => 'Family membership requires at least one dependent']);
            exit;
        }
        
        // Validate each dependent has required fields
        foreach ($dependents as $index => $dependent) {
            if (empty($dependent['first_name']) || empty($dependent['last_name']) || empty($dependent['relationship'])) {
                echo json_encode(['success' => false, 'message' => "Dependent " . ($index + 1) . " requires first name, last name, and relationship"]);
                exit;
            }
        }
    }
    
    // Check if email already exists
    $stmt = $pdo->prepare("SELECT id FROM members WHERE email = ?");
    $stmt->execute([$_POST['email']]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Email already exists']);
        exit;
    }
    
    // Generate auto KSO ID
    try {
        $pdo->query("INSERT INTO kso_id_sequence () VALUES ()");
        $sequence_id = $pdo->lastInsertId();
    } catch (Exception $e) {
        // If kso_id_sequence table doesn't exist, create it
        $pdo->exec("CREATE TABLE IF NOT EXISTS `kso_id_sequence` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `created_at` timestamp DEFAULT current_timestamp(),
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
        
        // Insert initial record and get ID
        $pdo->query("INSERT INTO kso_id_sequence () VALUES ()");
        $sequence_id = $pdo->lastInsertId();
    }
    
    $kso_id = 'KSOCHD' . str_pad($sequence_id, 3, '0', STR_PAD_LEFT);
    
    // Generate default password (can be changed later)
    $default_password = password_hash('kso@2025', PASSWORD_DEFAULT);
    
    // Handle file uploads
    $upload_dir = '../uploads/members/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $photo_url = null;
    
    // Handle profile photo upload
    if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
        $photo_extension = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
        $photo_filename = $kso_id . '_photo.' . $photo_extension;
        if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $upload_dir . $photo_filename)) {
            $photo_url = 'uploads/members/' . $photo_filename;
        }
    }

    // Set membership expiry date based on membership type
    $membership_expiry = null;
    if (!empty($_POST['membership_expiry_date'])) {
        $membership_expiry = $_POST['membership_expiry_date'];
    } else {
        // Default to 1 year from now
        $membership_expiry = date('Y-m-d', strtotime('+1 year'));
    }

    // Insert member data using only actual database columns
    $stmt = $pdo->prepare("
        INSERT INTO members (
            kso_id, first_name, last_name, nickname, email, password_hash, 
            phone, date_of_birth, gender, blood_group, college, course, 
            year_of_study, address, emergency_contact_name, emergency_contact,
            membership_type, status, photo_url, photo_id, notes, 
            membership_expiry_date, session_from_year, session_to_year,
            created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");
    
    $result = $stmt->execute([
        $kso_id,
        $_POST['first_name'],
        $_POST['last_name'],
        $_POST['nickname'] ?? null,
        $_POST['email'],
        $default_password,
        $_POST['phone'],
        $_POST['date_of_birth'] ?? null,
        $_POST['gender'] ?? null,
        $_POST['blood_group'] ?? null,
        $_POST['college'],
        $_POST['course'],
        $_POST['year_of_study'] ?? null,
        $_POST['address'] ?? null,
        $_POST['emergency_contact_name'] ?? null,
        $_POST['emergency_contact'] ?? null,
        $_POST['membership_type'],
        'pending', // Default status
        $photo_url,
        $_POST['photo_id'] ?? null,
        $_POST['notes'] ?? null,
        $membership_expiry,
        $_POST['session_from_year'] ?? null,
        $_POST['session_to_year'] ?? null
    ]);
    
    if ($result) {
        $member_id = $pdo->lastInsertId();
        
        // If family membership, insert dependents
        if ($_POST['membership_type'] === 'Family') {
            $dependents = json_decode($_POST['dependents'] ?? '[]', true);
            if (!empty($dependents)) {
                $dependent_stmt = $pdo->prepare("
                    INSERT INTO dependents (
                        member_id, first_name, last_name, relationship, 
                        date_of_birth, gender, phone, email
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                
                foreach ($dependents as $dependent) {
                    $dependent_stmt->execute([
                        $member_id,
                        $dependent['first_name'],
                        $dependent['last_name'],
                        $dependent['relationship'],
                        $dependent['date_of_birth'] ?? null,
                        $dependent['gender'] ?? null,
                        $dependent['phone'] ?? null,
                        $dependent['email'] ?? null
                    ]);
                }
            }
        }
        
        echo json_encode([
            'success' => true, 
            'message' => 'Member registered successfully',
            'kso_id' => $kso_id,
            'member_id' => $member_id,
            'membership_type' => $_POST['membership_type']
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to register member']);
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Registration failed: ' . $e->getMessage()
    ]);
}
?>
                $_POST['how_did_you_hear'] ?? null
            ]);
        } catch (Exception $e) {
            // Create member_profiles table if it doesn't exist
            $pdo->exec("CREATE TABLE IF NOT EXISTS `member_profiles` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `member_id` int(11) NOT NULL,
              `city` varchar(100) DEFAULT NULL,
              `state` varchar(100) DEFAULT NULL,
              `pin_code` varchar(10) DEFAULT NULL,
              `occupation` varchar(100) DEFAULT NULL,
              `organization` varchar(200) DEFAULT NULL,
              `designation` varchar(100) DEFAULT NULL,
              `annual_income` decimal(10,2) DEFAULT NULL,
              `education_level` varchar(50) DEFAULT NULL,
              `field_of_study` varchar(100) DEFAULT NULL,
              `how_did_you_hear` varchar(100) DEFAULT NULL,
              `created_at` datetime DEFAULT current_timestamp(),
              `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `member_id` (`member_id`),
              KEY `idx_city` (`city`),
              KEY `idx_state` (`state`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
            
            // Try inserting again
            $profile_stmt->execute([
                $member_id,
                $_POST['city'] ?? null,
                $_POST['state'] ?? null,
                $_POST['pin_code'] ?? null,
                $_POST['occupation'] ?? null,
                $_POST['organization'] ?? null,
                $_POST['designation'] ?? null,
                $_POST['annual_income'] ?? null,
                $_POST['education_level'] ?? null,
                $_POST['field_of_study'] ?? null,
                $_POST['how_did_you_hear'] ?? null
            ]);
        }
        
        // Store document URLs in a documents table if needed
        if ($id_proof_url || $address_proof_url) {
            $doc_stmt = $pdo->prepare("
                INSERT INTO member_documents (member_id, document_type, file_path, uploaded_at) 
                VALUES (?, ?, ?, NOW())
            ");
            
            if ($id_proof_url) {
                try {
                    $doc_stmt->execute([$member_id, 'id_proof', $id_proof_url]);
                } catch (Exception $e) {
                    // Create table if it doesn't exist
                    $pdo->exec("CREATE TABLE IF NOT EXISTS `member_documents` (
                      `id` int(11) NOT NULL AUTO_INCREMENT,
                      `member_id` int(11) NOT NULL,
                      `document_type` varchar(50) NOT NULL,
                      `file_path` varchar(500) NOT NULL,
                      `uploaded_at` datetime DEFAULT current_timestamp(),
                      PRIMARY KEY (`id`),
                      KEY `idx_member_id` (`member_id`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
                    
                    $doc_stmt->execute([$member_id, 'id_proof', $id_proof_url]);
                }
            }
            
            if ($address_proof_url) {
                $doc_stmt->execute([$member_id, 'address_proof', $address_proof_url]);
            }
        }
        
        // Log activity
        $admin_id = $_SESSION['admin_id'] ?? 1;
        $pdo->prepare("
            INSERT INTO activity_logs (user_id, action, details, ip_address, created_at) 
            VALUES (?, 'member_registered', ?, ?, NOW())
        ")->execute([
            $admin_id, 
            "Registered new member: {$_POST['first_name']} {$_POST['last_name']} (KSO ID: {$kso_id})", 
            $_SERVER['REMOTE_ADDR']
        ]);
        
        echo json_encode([
            'success' => true, 
            'message' => 'Member registered successfully',
            'member_id' => $member_id,
            'kso_id' => $kso_id,
            'default_password' => 'kso@2025'
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to register member']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
