<?php
// member/api/update-organization.php
require_once '../../config.php';
requireLogin();

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

$userId = $_SESSION['user_id'];
$org = getUserOrganization($userId);
$pdo = getDBConnection();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    // Update organization main details
    $stmt = $pdo->prepare("UPDATE organizations SET 
        name = ?,
        website = ?,
        industry = ?,
        size = ?,
        registration_number = ?,
        email = ?,
        phone = ?,
        address = ?,
        updated_at = NOW()
        WHERE id = ?");
    
    $stmt->execute([
        $_POST['organization_name'] ?? '',
        $_POST['website'] ?? '',
        $_POST['industry'] ?? '',
        $_POST['size'] ?? '',
        $_POST['registration_number'] ?? '',
        $_POST['email'] ?? '',
        $_POST['phone'] ?? '',
        $_POST['address'] ?? '',
        $org['id'] ?? 0
    ]);
    
    // Update or insert DPO details
    if (!empty($_POST['dpo_name']) && !empty($_POST['dpo_email'])) {
        // Check if DPO exists
        $stmt = $pdo->prepare("SELECT id FROM organization_dpo WHERE organization_id = ?");
        $stmt->execute([$org['id'] ?? 0]);
        $existingDpo = $stmt->fetch();
        
        if ($existingDpo) {
            $stmt = $pdo->prepare("UPDATE organization_dpo SET 
                name = ?,
                email = ?,
                phone = ?,
                updated_at = NOW()
                WHERE organization_id = ?");
            $stmt->execute([
                $_POST['dpo_name'],
                $_POST['dpo_email'],
                $_POST['dpo_phone'] ?? '',
                $org['id'] ?? 0
            ]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO organization_dpo 
                (organization_id, name, email, phone, dpo_type, contact_published, status, created_at) 
                VALUES (?, ?, ?, ?, 'internal', 1, 'active', NOW())");
            $stmt->execute([
                $org['id'] ?? 0,
                $_POST['dpo_name'],
                $_POST['dpo_email'],
                $_POST['dpo_phone'] ?? ''
            ]);
        }
    }
    
    // Log activity
    $stmt = $pdo->prepare("INSERT INTO user_activity (user_id, action, details, ip_address, created_at) 
                           VALUES (?, 'organization_update', 'Updated organization profile', ?, NOW())");
    $stmt->execute([$userId, $_SERVER['REMOTE_ADDR'] ?? '']);
    
    $pdo->commit();
    
    echo json_encode(['success' => true, 'message' => 'Organization updated successfully']);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Update failed: ' . $e->getMessage()]);
}