# Satoshi — Bitcoin portfolio tracker A self-hosted PHP and MySQL application for tracking manually entered Bitcoin purchases and sales, with an administrator console and member-selected contribution goals. It does not hold cryptocurrency, connect to an exchange, or execute trades. ## Requirements - PHP 7.4 or later with PDO MySQL and GD enabled - MySQL 5.7+ or MariaDB 10.3+ - A web server such as Apache (included with XAMPP) - PHP Fileinfo enabled for profile-image validation (enabled in standard XAMPP installs) - Internet access in the browser for live Bitcoin pricing from CoinGecko ## Setup with XAMPP 1. Copy this project into `C:\xampp\htdocs\investment`. 2. Start **Apache** and **MySQL** from the XAMPP Control Panel. 3. Open phpMyAdmin at `http://localhost/phpmyadmin`. 4. Import the single `database.sql` file using the **Import** tab. It creates the main `btc_investment` database and the separate `btc_investment_records` database, with their complete current schemas. If upgrading an existing installation, run this once in phpMyAdmin's SQL tab to enable banner image uploads: ```sql ALTER TABLE btc_investment.adverts ADD COLUMN image_data MEDIUMBLOB NULL AFTER target_url, ADD COLUMN image_mime VARCHAR(40) NULL AFTER image_data; ``` 5. Open `http://localhost/investment/` and create an account. 6. Create the requested starter administrator from an XAMPP Shell or PowerShell window: ```powershell & 'C:\xampp\php\php.exe' 'C:\xampp\htdocs\investment\create_admin.php' ``` The setup creates separate **Super Admin** (`superadmin`) and **Admin** (`admin`) accounts for local XAMPP use. Open `http://localhost/investment/admin/` to sign in. The admin portal uses its own private login page and an independent session; customers see no admin links in the portfolio. Super Admin can grant or remove Super Admin access, while Admin cannot manage Super Admin accounts. The setup command is CLI-only and is safe to rerun without resetting existing passwords. Local starter passwords are not suitable for internet hosting. On an existing local installation, the optional reset flag restores the local starter passwords: ```powershell & 'C:\xampp\php\php.exe' 'C:\xampp\htdocs\investment\create_admin.php' '--reset-starter-credentials' ``` This option renames the legacy Super Admin login `admin@admin.com` to `superadmin` and resets both account passwords. Do not use it on a hosted database without supplying strong initial passwords as described below. In the admin console, set verified Mobile Money network, recipient name, number, and instructions under **Mobile Money** before accepting member deposit references. Leave these blank until the details are confirmed. Under **Adverts**, admins can upload optional JPEG, PNG, or WebP banner images up to 2 MB. Images are validated, resized, converted to WebP, and stored with the advert. Wide landscape images work best. > Local starter passwords are for XAMPP testing only. Replace them with long, unique passwords before any internet-facing deployment. ### Deploying on Hostinger 1. In hPanel, create a MySQL database and user, then assign that user to the database. Use the exact database name, username, host, and password Hostinger displays; its database names are commonly prefixed. 2. Download `database.sql` and edit a deployment copy. Replace both `btc_investment` references with the exact primary database name. Remove the first `CREATE DATABASE IF NOT EXISTS ...` statement (including its character-set and collation lines), but keep the matching `USE` statement. Hostinger creates databases in hPanel, and the database user may not have permission to create them. 3. The optional investment-record services use a second database. If you need those services, create a second database in hPanel, assign the same user to it, replace `btc_investment_records` with its exact name, and remove that section's `CREATE DATABASE` statement too. If you only use the public portfolio and admin site, omit the optional section beginning `-- Optional investment-record services use a separate database.` from the deployment copy. 4. Import the edited SQL in phpMyAdmin. Import it only into a new database. Do not re-import it over an existing database: the `ALTER TABLE` and seed steps are for a fresh install and are not an in-place upgrade. 5. Upload the application files to the domain's document root (usually `public_html`). Copy `config.local.example.php` to `config.local.php` and enter the exact primary database host, name, username, and password in the `DB_*` entries. If using the optional investment-record services, enter their separate credentials in the `INVESTMENT_DB_*` entries too. The application prefers server environment variables when present and otherwise reads this local file. Keep the root `.htaccess` in place; it denies direct requests for `config.local.php`. The file is also excluded by `.gitignore`. 6. In hPanel's PHP configuration, enable PDO MySQL, GD, Fileinfo, cURL, and OpenSSL. Use a currently supported PHP version compatible with the site; PHP 8.1 or later is recommended. 7. Enable the SSL certificate and force HTTPS in hPanel before allowing registrations or admin sign-ins. Confirm the domain points to the Hostinger hosting account. 8. Create or secure admin accounts from Hostinger Terminal in the application's document-root directory. The script reads the database credentials from `config.local.php`; for a hosted database it requires separate initial passwords of 12-72 characters. Enter them without putting them in shell history, then run the script. If you imported a database copied from local XAMPP, add `--reset-starter-credentials` to replace any local starter passwords: ```sh read -r -s -p "Admin initial password: " ADMIN_INITIAL_PASSWORD; printf '\n' export ADMIN_INITIAL_PASSWORD read -r -s -p "Super Admin initial password: " SUPER_ADMIN_INITIAL_PASSWORD; printf '\n' export SUPER_ADMIN_INITIAL_PASSWORD php create_admin.php --reset-starter-credentials unset ADMIN_INITIAL_PASSWORD SUPER_ADMIN_INITIAL_PASSWORD ``` The reset flag changes both admin passwords. For a new database with no admin accounts, omit the flag. Remove `create_admin.php` after bootstrap. 9. Test new account registration, sign-in, admin sign-in, profile updates, CSV export, and the admin advert page. Keep regular database backups and never use the app to accept real deposits or promise investment returns; it is a manual portfolio tracker, not a payment processor or trading platform. The root `.htaccess` disables directory listings and blocks direct web requests for database/configuration files, internal library files, CLI-only scripts, logs, backups, and INI files. Keep this file when uploading to Hostinger. ### Standalone investment-record schema and PDO connection `Database.php`, `Auth.php`, `Investment.php`, `Transaction.php`, and `calculate_roi.php` provide a separate investment-record schema, PDO singleton, authentication backend, investment and transaction services, and CLI demo simulation. The `btc_investment_records` schema is included in `database.sql`; it is independent of the portfolio tracker's `btc_investment` database. The connection class reads `INVESTMENT_DB_HOST`, `INVESTMENT_DB_NAME`, `INVESTMENT_DB_USER`, and `INVESTMENT_DB_PASS`; defaults are `127.0.0.1`, `btc_investment_records`, `root`, and an empty password for local XAMPP only. These separate variable names prevent it from accidentally using the portfolio tracker's `DB_*` settings. Configure a dedicated, least-privilege MySQL account and a strong password before exposing the database beyond localhost. Include `Database.php` and retrieve the PDO connection with `Database::getInstance()->getConnection()`. Include `Auth.php` and use `register()` to create an account, `login()` to establish its secure session, and `logout()` to clear it. Registration requires a 3-50 character username, a login identifier (which may be an email or a simple name), and a 4-72 byte password; a blank wallet address is stored as `NULL`. `Investment.php` calculates BTC at CoinGecko's current BTC/USD quote and stores a pending investment; it requires PHP's cURL extension and throws an exception if the price API times out, fails, or returns an invalid response. `getUserInvestments()` returns all investment statuses for only the supplied user ID. This tracker records requests and does not execute purchases or guarantee returns. `calculate_roi.php` is CLI-only and adds a daily 1% **demo simulation** record for active investments; it does not update spendable balances, and the `earnings.is_simulated` flag distinguishes these records from actual earnings. This is not a real or guaranteed investment return. The script is idempotent per investment/day and commits or rolls back the whole batch. Example Windows scheduled task command: `C:\xampp\php\php.exe C:\xampp\htdocs\investment\calculate_roi.php`. `Transaction.php` verifies only a deposit transaction already recorded with its `investment_id`, then atomically confirms the deposit and activates its linked pending investment once the mock lookup reports at least three confirmations. The default mock fails closed; inject a `Closure` returning `['found' => true, 'confirmations' => 3]` only in controlled tests. This is not real blockchain verification and must not be used to credit actual deposits. A production verifier must validate the Bitcoin network, destination address, output amount, and confirmations against a trusted node/provider. Withdrawal requests are reserved atomically as `pending_admin_review` transactions. Available balance is calculated only from non-simulated `earnings.amount_btc`, less pending-review and confirmed withdrawals. Simulated USD ROI entries never count as withdrawable BTC. Approving and paying a withdrawal should transition it to `confirmed`; rejecting it should transition it to `rejected`, which releases the reservation. ### Existing installations `database.sql` is a complete installer for a new hosting account, not an in-place upgrade. Do not import it over an existing database: it will not migrate existing tables and you should preserve your data. Back up existing databases before any schema changes. Admin-managed public adverts are configured in the separate admin console under **Adverts**; only active adverts appear on the public welcome page, and links must use `http` or `https`. To enable Super Admin on a database created with an older version, back it up, then run `ALTER TABLE users MODIFY role ENUM('user', 'admin', 'super_admin') NOT NULL DEFAULT 'user';` once in phpMyAdmin before running `create_admin.php`. This updates the existing role column without replacing account or transaction data. The default local database connection is `127.0.0.1`, database `btc_investment`, user `root`, and an empty password. For a different database, set `DB_HOST`, `DB_NAME`, `DB_USER`, and `DB_PASS` in the PHP/Apache environment before starting Apache. ## Features - Account registration and sign-in with password hashing and per-account transaction isolation. - Customer profile settings for updating name, email, and phone number, uploading or removing a JPEG/PNG/WebP profile photo (2 MB and 20-megapixel limits), and explicitly signing out. Profile images are validated and stored with the account; phone numbers are required for new signups. - A separate, unlinked administrator portal at `/investment/admin/`, with its own username/password sign-in, strict session cookie, role checks, and login rate limiting. Customer pages have no links to the admin area. - Separate Super Admin and Admin accounts created by the CLI-only setup command. A hosted database requires configured initial passwords of at least 12 characters; public registration cannot select administrator privileges. - A role-protected administrator console for creating members, editing account details, assigning admin access, suspending accounts, searching members, managing plans, and reviewing enrollments. Administrators cannot suspend or demote themselves, and the last active administrator cannot be demoted or suspended. - Administrator profile settings for updating the admin's own display name, login name/email, optional phone number, and JPEG/PNG/WebP profile photo. - Seven seeded member-selected contribution goals across weekly, biweekly, and monthly schedules, with estimated contribution targets, progress linked to manually recorded BTC buys, frequency filters, and cancellation that preserves history. Targets are tracking estimates, not returns or automatic payments. - Manual BTC buy/sell ledger with quantity, GHS price, fees, and transaction date. - Member Mobile Money deposit instructions and submitted payment references, plus GHS withdrawal requests with administrator-reviewed statuses. Admins must verify deposits against their provider and send approved payouts manually; this app does not collect, hold, or transfer money. - A per-account CSV statement download combining BTC ledger activity and deposit/withdrawal request history. Since historical FX rates are not stored, BTC amounts in the export are converted to GHS using the live rate at download time. - Average-cost basis accounting. Adding a backdated transaction recalculates later cost basis and realized profit/loss; a sale that would create a negative historical balance is rejected. - Dashboard with BTC balance, remaining cost basis, live portfolio value, realized and unrealized profit/loss, and recent activity. - The public welcome page keeps sign-in and account creation closed until the visitor requests them; both open in a dismissible sign-in panel. Signed-in dashboard sections open on demand from the horizontal desktop header or mobile bottom navigation; the overview, contribution plans, transactions, and account settings display as separate views. Within Transactions, deposit instructions, withdrawal forms, payment history, and Bitcoin history remain hidden until the member taps the corresponding button. Live market pricing and GHS conversion load when the portfolio opens, and asset URLs are automatically versioned so browsers receive the latest CSS and JavaScript after updates. - The public landing page highlights Bitcoin and major global companies such as Alphabet/Google, Tesla, Apple, Microsoft, NVIDIA, Amazon, and Meta. These are informational references only; the tracker does not provide equity quotes or share trading. - Admin-managed, clearly labeled public promotional cards with editable title, description, button text, destination URL, and publish status. - Live BTC/GHS price and 24-hour change loaded from CoinGecko. Portfolio values and plan amounts are displayed in Ghana cedis; transaction and plan inputs accept GHS and are normalized to the existing USD database columns using the live BTC/USD-to-BTC/GHS exchange ratio. If the provider is unavailable, currency values report as unavailable rather than showing a fabricated conversion. - CSRF protection, parameterized database queries, secure password hashes, session ID rotation, and escaped HTML output. - Plan amounts are tracking goals only. No money is collected, no BTC is purchased automatically, and no returns are projected or promised. ## Accounting notes Buy fees are added to purchase cost basis. Sell fees are subtracted from sale proceeds. For a sale, the average cost of the BTC held immediately before that transaction is allocated to the quantity sold. All displayed amounts are informational and depend on the transactions entered by the account holder. This application is a portfolio tracker, not investment advice, a broker, an exchange, or a wallet. It does not store private keys or move funds. Keep PHP, MySQL, and the host operating system updated, and use HTTPS if you expose the application beyond your local machine.