<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, User-ID');

require_once '../config/database.php';
require_once '../config/auth.php';

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Check authentication
$auth = new Auth();
if (!$auth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];
$endpoint = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($endpoint);
            break;
        case 'POST':
            handlePostRequest($endpoint);
            break;
        case 'PUT':
            handlePutRequest($endpoint);
            break;
        case 'DELETE':
            handleDeleteRequest($endpoint);
            break;
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Internal server error: ' . $e->getMessage()]);
}

function handleGetRequest($endpoint) {
    global $pdo;
    
    switch ($endpoint) {
        case 'download-csv':
            downloadCSV();
            break;
        case 'get-panchang':
            getPanchangData();
            break;
        case 'get-stats':
            getPanchangStats();
            break;
        case 'get-backups':
            getAvailableBackups();
            break;
        default:
            http_response_code(404);
            echo json_encode(['error' => 'Endpoint not found']);
            break;
    }
}

function handlePostRequest($endpoint) {
    global $pdo;
    
    switch ($endpoint) {
        case 'upload-csv':
            uploadCSV();
            break;
        case 'sync-panchang':
            syncPanchangData();
            break;
        case 'validate-csv':
            validateCSV();
            break;
        case 'backup':
            backupPanchangData();
            break;
        case 'restore':
            restorePanchangData();
            break;
        default:
            http_response_code(404);
            echo json_encode(['error' => 'Endpoint not found']);
            break;
    }
}

function handlePutRequest($endpoint) {
    global $pdo;
    
    if ($endpoint === 'update-panchang') {
        updatePanchangEntry();
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
    }
}

function handleDeleteRequest($endpoint) {
    global $pdo;
    
    if ($endpoint === 'delete-panchang') {
        deletePanchangEntry();
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
    }
}

// CSV Upload Function
function uploadCSV() {
    global $pdo;
    
    if (!isset($_FILES['csv_file'])) {
        http_response_code(400);
        echo json_encode(['error' => 'No CSV file uploaded']);
        return;
    }
    
    $file = $_FILES['csv_file'];
    $fileName = $file['name'];
    $fileTmpPath = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileType = $file['type'];
    
    // Validate file type
    if ($fileType !== 'text/csv' && $fileType !== 'application/vnd.ms-excel') {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid file type. Only CSV files are allowed.']);
        return;
    }
    
    // Validate file size (max 5MB)
    if ($fileSize > 5 * 1024 * 1024) {
        http_response_code(400);
        echo json_encode(['error' => 'File size too large. Maximum size is 5MB.']);
        return;
    }
    
    try {
        // Read CSV content
        $csvContent = file_get_contents($fileTmpPath);
        $lines = explode("\n", $csvContent);
        
        // Parse CSV headers
        $headers = str_getcsv($lines[0]);
        
        // Validate required headers
        $requiredHeaders = ['Date', 'Tithi (मुख्य)'];
        foreach ($requiredHeaders as $header) {
            if (!in_array($header, $headers)) {
                http_response_code(400);
                echo json_encode(['error' => "Missing required header: $header"]);
                return;
            }
        }
        
        // Clear existing data
        $stmt = $pdo->prepare("DELETE FROM panchang_data");
        $stmt->execute();
        
        // Insert new data
        $insertStmt = $pdo->prepare("
            INSERT INTO panchang_data (date, tithi, nakshatra, yoga, karana, muhurat, rahu_kaal, gulika_kaal, sunrise, sunset, moonrise, moonset, special_day, festival, remarks, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");
        
        $successCount = 0;
        $errorCount = 0;
        
        for ($i = 1; $i < count($lines); $i++) {
            if (trim($lines[$i]) === '') continue;
            
            $data = str_getcsv($lines[$i]);
            if (count($data) < 2) continue;
            
            try {
                $insertStmt->execute([
                    $data[0] ?? '', // Date
                    $data[1] ?? '', // Tithi
                    $data[2] ?? '', // Nakshatra
                    $data[3] ?? '', // Yoga
                    $data[4] ?? '', // Karana
                    $data[5] ?? '', // Muhurat
                    $data[6] ?? '', // Rahu Kaal
                    $data[7] ?? '', // Gulika Kaal
                    $data[8] ?? '', // Sunrise
                    $data[9] ?? '', // Sunset
                    $data[10] ?? '', // Moonrise
                    $data[11] ?? '', // Moonset
                    $data[12] ?? '', // Special Day
                    $data[13] ?? '', // Festival
                    $data[14] ?? '', // Remarks
                ]);
                $successCount++;
            } catch (Exception $e) {
                $errorCount++;
                error_log("Error inserting row $i: " . $e->getMessage());
            }
        }
        
        // Log the upload
        $adminId = $_SESSION['admin_id'] ?? 0;
        $logStmt = $pdo->prepare("
            INSERT INTO admin_logs (admin_id, action, details, created_at)
            VALUES (?, 'CSV_UPLOAD', ?, NOW())
        ");
        $logStmt->execute([$adminId, "Uploaded $fileName: $successCount successful, $errorCount errors"]);
        
        echo json_encode([
            'success' => true,
            'message' => 'CSV uploaded successfully',
            'success_count' => $successCount,
            'error_count' => $errorCount,
            'total_rows' => count($lines) - 1
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error processing CSV: ' . $e->getMessage()]);
    }
}

// Download CSV Function
function downloadCSV() {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT date, tithi, nakshatra, yoga, karana, muhurat, rahu_kaal, gulika_kaal, sunrise, sunset, moonrise, moonset, special_day, festival, remarks
            FROM panchang_data
            ORDER BY date ASC
        ");
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($data)) {
            http_response_code(404);
            echo json_encode(['error' => 'No Panchang data available']);
            return;
        }
        
        // Generate CSV content
        $csvContent = "Date,Tithi (मुख्य),Nakshatra,Yoga,Karana,Muhurat,Rahu Kaal,Gulika Kaal,Sunrise,Sunset,Moonrise,Moonset,Special Day,Festival,Remarks\n";
        
        foreach ($data as $row) {
            $csvContent .= implode(',', array_map(function($value) {
                return '"' . str_replace('"', '""', $value) . '"';
            }, $row)) . "\n";
        }
        
        // Set headers for download
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="panchang_data_' . date('Y-m-d') . '.csv"');
        header('Content-Length: ' . strlen($csvContent));
        
        echo $csvContent;
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error generating CSV: ' . $e->getMessage()]);
    }
}

// Get Panchang Data Function
function getPanchangData() {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT * FROM panchang_data
            ORDER BY date ASC
        ");
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'panchang_data' => $data,
            'total_entries' => count($data)
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching Panchang data: ' . $e->getMessage()]);
    }
}

// Update Panchang Entry Function
function updatePanchangEntry() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $date = $input['date'] ?? '';
    $updateData = $input['update_data'] ?? [];
    
    if (empty($date) || empty($updateData)) {
        http_response_code(400);
        echo json_encode(['error' => 'Date and update data are required']);
        return;
    }
    
    try {
        $fields = [];
        $values = [];
        
        foreach ($updateData as $key => $value) {
            if (in_array($key, ['date', 'tithi', 'nakshatra', 'yoga', 'karana', 'muhurat', 'rahu_kaal', 'gulika_kaal', 'sunrise', 'sunset', 'moonrise', 'moonset', 'special_day', 'festival', 'remarks'])) {
                $fields[] = "$key = ?";
                $values[] = $value;
            }
        }
        
        if (empty($fields)) {
            http_response_code(400);
            echo json_encode(['error' => 'No valid fields to update']);
            return;
        }
        
        $values[] = $date; // For WHERE clause
        
        $sql = "UPDATE panchang_data SET " . implode(', ', $fields) . ", updated_at = NOW() WHERE date = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($values);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'success' => true,
                'message' => 'Panchang entry updated successfully'
            ]);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Panchang entry not found']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error updating Panchang entry: ' . $e->getMessage()]);
    }
}

// Delete Panchang Entry Function
function deletePanchangEntry() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $date = $input['date'] ?? '';
    
    if (empty($date)) {
        http_response_code(400);
        echo json_encode(['error' => 'Date is required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM panchang_data WHERE date = ?");
        $stmt->execute([$date]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'success' => true,
                'message' => 'Panchang entry deleted successfully'
            ]);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Panchang entry not found']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error deleting Panchang entry: ' . $e->getMessage()]);
    }
}

// Get Panchang Stats Function
function getPanchangStats() {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as total_entries,
                COUNT(CASE WHEN tithi IS NOT NULL AND tithi != '' THEN 1 END) as entries_with_tithi,
                COUNT(CASE WHEN nakshatra IS NOT NULL AND nakshatra != '' THEN 1 END) as entries_with_nakshatra,
                MIN(date) as earliest_date,
                MAX(date) as latest_date,
                COUNT(CASE WHEN special_day IS NOT NULL AND special_day != '' THEN 1 END) as special_days,
                COUNT(CASE WHEN festival IS NOT NULL AND festival != '' THEN 1 END) as festivals
            FROM panchang_data
        ");
        $stmt->execute();
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'stats' => $stats
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching stats: ' . $e->getMessage()]);
    }
}

// Validate CSV Function
function validateCSV() {
    $input = json_decode(file_get_contents('php://input'), true);
    $csvContent = $input['csv_content'] ?? '';
    
    if (empty($csvContent)) {
        http_response_code(400);
        echo json_encode(['error' => 'CSV content is required']);
        return;
    }
    
    try {
        $lines = explode("\n", $csvContent);
        $errors = [];
        $warnings = [];
        
        if (count($lines) < 2) {
            $errors[] = 'CSV must have at least a header row and one data row';
        }
        
        // Validate headers
        if (count($lines) > 0) {
            $headers = str_getcsv($lines[0]);
            $requiredHeaders = ['Date', 'Tithi (मुख्य)'];
            
            foreach ($requiredHeaders as $header) {
                if (!in_array($header, $headers)) {
                    $errors[] = "Missing required header: $header";
                }
            }
        }
        
        // Validate data rows
        for ($i = 1; $i < count($lines); $i++) {
            if (trim($lines[$i]) === '') continue;
            
            $data = str_getcsv($lines[$i]);
            $rowNum = $i + 1;
            
            if (count($data) < 2) {
                $errors[] = "Row $rowNum: Insufficient data columns";
                continue;
            }
            
            // Validate date format
            if (!empty($data[0])) {
                if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $data[0])) {
                    $errors[] = "Row $rowNum: Invalid date format. Use YYYY-MM-DD";
                }
            }
            
            // Check for empty required fields
            if (empty($data[1])) {
                $warnings[] = "Row $rowNum: Tithi is empty";
            }
        }
        
        $isValid = empty($errors);
        
        echo json_encode([
            'success' => true,
            'valid' => $isValid,
            'errors' => $errors,
            'warnings' => $warnings,
            'total_rows' => count($lines) - 1
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error validating CSV: ' . $e->getMessage()]);
    }
}

// Sync Panchang Data Function
function syncPanchangData() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $localData = $input['local_data'] ?? [];
    $lastSync = $input['last_sync'] ?? '';
    
    try {
        // Get server data
        $stmt = $pdo->prepare("
            SELECT * FROM panchang_data
            WHERE updated_at > ?
            ORDER BY date ASC
        ");
        $stmt->execute([$lastSync]);
        $serverData = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Find conflicts and updates
        $conflicts = [];
        $updates = [];
        
        foreach ($localData as $local) {
            foreach ($serverData as $server) {
                if ($local['Date'] === $server['date']) {
                    if ($local['Tithi (मुख्य)'] !== $server['tithi']) {
                        $conflicts[] = [
                            'date' => $local['Date'],
                            'local' => $local,
                            'server' => $server
                        ];
                    }
                }
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Sync completed',
            'conflicts' => $conflicts,
            'updates' => $serverData,
            'server_time' => date('Y-m-d H:i:s')
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error syncing data: ' . $e->getMessage()]);
    }
}

// Backup Panchang Data Function
function backupPanchangData() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $data = $input['data'] ?? [];
    $version = $input['version'] ?? '1.0.0';
    
    try {
        $backupId = 'backup_' . date('Y_m_d_H_i_s');
        
        $stmt = $pdo->prepare("
            INSERT INTO panchang_backups (backup_id, data, version, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->execute([$backupId, json_encode($data), $version]);
        
        echo json_encode([
            'success' => true,
            'backup_id' => $backupId,
            'message' => 'Backup created successfully'
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error creating backup: ' . $e->getMessage()]);
    }
}

// Get Available Backups Function
function getAvailableBackups() {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT backup_id, version, created_at, data_size
            FROM panchang_backups
            ORDER BY created_at DESC
        ");
        $stmt->execute();
        $backups = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'backups' => $backups
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error fetching backups: ' . $e->getMessage()]);
    }
}

// Restore Panchang Data Function
function restorePanchangData() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $backupId = $input['backup_id'] ?? '';
    
    if (empty($backupId)) {
        http_response_code(400);
        echo json_encode(['error' => 'Backup ID is required']);
        return;
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT data FROM panchang_backups
            WHERE backup_id = ?
        ");
        $stmt->execute([$backupId]);
        $backup = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$backup) {
            http_response_code(404);
            echo json_encode(['error' => 'Backup not found']);
            return;
        }
        
        $data = json_decode($backup['data'], true);
        
        // Clear existing data
        $clearStmt = $pdo->prepare("DELETE FROM panchang_data");
        $clearStmt->execute();
        
        // Restore data
        $insertStmt = $pdo->prepare("
            INSERT INTO panchang_data (date, tithi, nakshatra, yoga, karana, muhurat, rahu_kaal, gulika_kaal, sunrise, sunset, moonrise, moonset, special_day, festival, remarks, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");
        
        foreach ($data as $row) {
            $insertStmt->execute([
                $row['Date'] ?? '',
                $row['Tithi (मुख्य)'] ?? '',
                $row['Nakshatra'] ?? '',
                $row['Yoga'] ?? '',
                $row['Karana'] ?? '',
                $row['Muhurat'] ?? '',
                $row['Rahu Kaal'] ?? '',
                $row['Gulika Kaal'] ?? '',
                $row['Sunrise'] ?? '',
                $row['Sunset'] ?? '',
                $row['Moonrise'] ?? '',
                $row['Moonset'] ?? '',
                $row['Special Day'] ?? '',
                $row['Festival'] ?? '',
                $row['Remarks'] ?? '',
            ]);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Backup restored successfully',
            'restored_entries' => count($data)
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error restoring backup: ' . $e->getMessage()]);
    }
}
?> 